﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SalaryChannel.PSSService;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows.Browser;
using SalaryChannel.ViewService;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Printing;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;
using System.Windows.Threading;

namespace SalaryChannel
{
    public partial class PSSControl : UserControl
    {
        private PSSServiceClient _pssService = null;
        private static OperationContext _pssPC = null;
        public PSSServiceClient PSSService
        {
            get
            {
                if (_pssService == null)
                {
                    _pssService = new PSSServiceClient();

                    OperationContext.Current = new OperationContext((IContextChannel)_pssService.InnerChannel);
                    MessageHeader header = MessageHeader.CreateHeader("uafcztga", "", ServiceInstance.UserName);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    header = MessageHeader.CreateHeader("xufasft", "", ServiceInstance.Password);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    _pssPC = OperationContext.Current;
                }
                else
                {
                    OperationContext.Current = _pssPC;
                }
                return _pssService;
            }
            set { _pssService = value; }
        }

        public PSSControl()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(PSSControl_Loaded);
            PSSService.GetProviderCompleted += new EventHandler<GetProviderCompletedEventArgs>(PSSService_GetProviderCompleted);
         

            PSSService.GetAllPSSReportCompleted += new EventHandler<GetAllPSSReportCompletedEventArgs>(PSSService_GetAllPSSReportCompleted);
            PSSService.GetReportByTableCompleted += new EventHandler<GetReportByTableCompletedEventArgs>(PSSService_GetReportByTableCompleted);
            PSSService.GetReportByFileCompleted += new EventHandler<GetReportByFileCompletedEventArgs>(PSSService_GetReportByFileCompleted);

            PSSService.Self_AddStorageCompleted += new EventHandler<Self_AddStorageCompletedEventArgs>(PSSService_Self_AddStorageCompleted);
            PSSService.Self_GetDeviceListByPIDCompleted += new EventHandler<Self_GetDeviceListByPIDCompletedEventArgs>(PSSService_Self_GetDeviceListByPIDCompleted);
            PSSService.Self_PayCompleted += new EventHandler<Self_PayCompletedEventArgs>(PSSService_Self_PayCompleted);
            PSSService.Self_UnStoreCompleted += new EventHandler<Self_UnStoreCompletedEventArgs>(PSSService_Self_UnStoreCompleted);
            PSSService.Self_GetDeviceStorageInfoCompleted += new EventHandler<Self_GetDeviceStorageInfoCompletedEventArgs>(PSSService_Self_GetDeviceStorageInfoCompleted);
            PSSService.Self_BillCompleted += new EventHandler<Self_BillCompletedEventArgs>(PSSService_Self_BillCompleted);
             BigTab.SelectionChanged += new SelectionChangedEventHandler(BigTab_SelectionChanged);
            PSSService.Self_UnSaleCompleted += new EventHandler<Self_UnSaleCompletedEventArgs>(PSSService_Self_UnSaleCompleted);

            PSSService.GetProvderByNameCompleted += new EventHandler<GetProvderByNameCompletedEventArgs>(PSSService_GetProvderByNameCompleted);
            PSSService.CreateProviderCompleted += new EventHandler<CreateProviderCompletedEventArgs>(PSSService_CreateProviderCompleted);
            PSSService.UpdateProviderCompleted += new EventHandler<UpdateProviderCompletedEventArgs>(PSSService_UpdateProviderCompleted);
            PSSService.GetDeviceDetailByIDCompleted += new EventHandler<GetDeviceDetailByIDCompletedEventArgs>(PSSService_GetDeviceDetailByIDCompleted);
            PSSService.CreateDeviceCompleted += new EventHandler<CreateDeviceCompletedEventArgs>(PSSService_CreateDeviceCompleted);
            PSSService.UpdateDeviceCompleted += new EventHandler<UpdateDeviceCompletedEventArgs>(PSSService_UpdateDeviceCompleted);
            PSSService.DelDeviceCompleted += new EventHandler<DelDeviceCompletedEventArgs>(PSSService_DelDeviceCompleted);
            PSSService.GetScoreHisCompleted += new EventHandler<GetScoreHisCompletedEventArgs>(PSSService_GetScoreHisCompleted);
            PSSService.ExchangeScoreCompleted += new EventHandler<ExchangeScoreCompletedEventArgs>(PSSService_ExchangeScoreCompleted);
            PSSService.GetValidGiftCompleted += new EventHandler<GetValidGiftCompletedEventArgs>(PSSService_GetGiftCompleted);

            Mng_DeviceListCB.SelectionChanged += new SelectionChangedEventHandler(Mng_DeviceListC_SelectionChanged);

            SelfProviderCB.SelectionChanged += new SelectionChangedEventHandler(SelfProvidersssCB_SelectionChanged);

            PSSService.UnExchangeScoreCompleted += new EventHandler<UnExchangeScoreCompletedEventArgs>(PSSService_UnExchangeScoreCompleted);

            PSSService.GroupTHSendVerifyCodeCompleted += PSSService_GroupTHSendVerifyCodeCompleted;
        }

      
        

       
        void BigTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (BigTab.SelectedItem != null)
            {
                if (BigTab.SelectedItem == DevicePage)
                {
                    if (Mng_DeviceListCB.Items.Count == 0)
                    {
                        try
                        {
                            //终端维护，所有终端查询
                            PSSService.Self_GetDeviceListByPIDAsync(true);
                            selfLoading.Show();
                        }
                        catch
                        {
                            App.MessageBox.ShowDialog("发起获取供应商及终端信息失败");
                        }
                    }
                }
            }
        }

        void PSSControl_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        public void Initiallize()
        {
            ClearCreatePage();
            ClearListPage();
            BigTab.SelectedIndex = 4;

            ProviderCBox.Items.Clear();
            ListProviderCBox.Items.Clear();
            SelfProviderCB.Items.Clear();
            IsReprint = false;
            
            if (MyWorkPage.Tag == null
                || !MyWorkPage.Tag.Equals(App.CurrentUser.UserID))
            {
                PSSService.GetMyWorkAsync(App.CurrentUser.UserID);
            }
            UnpurIMEITB.Text = string.Empty;
            UnpurIMEIGrid.ItemsSource = null;

            ReportNameCBox.SelectedIndex = -1;
            ReEndDP.Text = DateTime.Today.ToShortDateString();
            ReStartDP.Text = DateTime.Today.ToShortDateString();
            ReportGrid.ItemsSource = null;
            
            ProviderPage.Visibility = App.IsAuth(22) ? Visibility.Visible : Visibility.Collapsed;
            DevicePage.Visibility = ProviderPage.Visibility;
          
            if (ProviderPage.Visibility == Visibility.Visible)
            {
                ClearProviderPage();
            }
            if (CreatePage.Visibility == Visibility.Visible)
            {
                UnpurchasePage.Visibility = (App.CurrentUser.ProviderID == -1) ? Visibility.Visible : Visibility.Collapsed;
            }
            if (ReportNameCBox.Items.Count == 0)
            {
                PSSService.GetAllPSSReportAsync(Guid.NewGuid());
            }

            if (App.IsAuth(23) || App.IsAuth(24) || App.IsAuth(25))
            {
                SelfPromoPage.Visibility = Visibility.Visible;
                //SelfTypeCB.IsEnabled = App.IsAuth(24);
                SelfTypeCB.Items.Clear();
                if (App.IsAuth(23))
                {
                    SelfTypeCB.Items.Add("销售");
                }
                if (App.IsAuth(24))
                {
                    SelfTypeCB.Items.Add("入库");

                }
                if (App.IsAuth(26))
                {
                    SelfTypeCB.Items.Add("对账");
                }
                SelfTypeCB.SelectedIndex = SelfTypeCB.Items.Count > 0 ? 0 : -1;

                SelfSaleBtn.Visibility = App.IsAuth(23) ? Visibility.Visible:Visibility.Collapsed;
                SelfUnStoreBtn.Visibility = App.IsAuth(24) ? Visibility.Visible : Visibility.Collapsed;
                UnSaleBtn.Visibility = App.IsAuth(28) ? Visibility.Visible : Visibility.Collapsed;
                ReprintBtn.Visibility = App.IsAuth(29) ? Visibility.Visible : Visibility.Collapsed;

                SelfBillDatePicker.SelectedDate = DateTime.Today;
                
            }
            else
            {
                SelfPromoPage.Visibility = Visibility.Collapsed;
            }

            if (App.IsAuthOnly(36))
            {//按销售价一口价销售
                SelfSaleTotalValueTB.IsReadOnly = true;
            }
            else
            {
                SelfSaleTotalValueTB.IsReadOnly = false;
            }
            SelfSaleTotalValueTB.Text = string.Empty;
        }

        /// <summary>
        /// 初始化供应商信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PSSService_GetProviderCompleted(object sender, GetProviderCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取供应商失败，无法预订");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("无有效供应商，无法预订");
                }
                else
                {
                    foreach (string s in e.Result)
                    {
                        //ProviderCBox.Items.Add(s);
                        SelfProviderCB.Items.Add(s);
                    }
                   

                    //if (ListProviderCBox.Items.Count == 0)
                    //{
                    //    ListProviderCBox.Items.Add("[-1]全部");
                    //    foreach (var s in e.Result)
                    //    {
                    //        ListProviderCBox.Items.Add(s);
                    //    }
                    //}
                    //ProviderCBox.IsEnabled = App.CurrentUser.ProviderID == -1;

                    //ListProviderCBox.IsEnabled = App.CurrentUser.ProviderID == -1;
                   
                    //if (App.CurrentUser.ProviderID == -1)
                    //{//非供应商
                    //    ProviderCBox.SelectedIndex = 0;
                    //    ListProviderCBox.SelectedIndex = 0;
                    //}
                    //else
                    //{
                    //    //供应商只能看到自己的终端
                    //    int i = 0;
                    //    for (; i < e.Result.Count; i++)
                    //    {
                    //        if (e.Result[i].StartsWith("[" + App.CurrentUser.ProviderID.ToString() + "]"))
                    //        {
                    //            ProviderCBox.SelectedIndex = i;
                    //            ListProviderCBox.SelectedIndex = i+1;
                    //            break;
                    //        }
                    //    }
                    //    if (i >= e.Result.Count)
                    //    {
                    //        ProviderCBox.SelectedIndex = -1;
                    //        ListProviderCBox.SelectedIndex = -1;
                    //        App.MessageBox.ShowDialog("您的供应商信息不合法");
                    //    }
                    //}
                    

                    ClearListPage();

                }
            }
            catch
            {

                App.MessageBox.ShowDialog("获取供应商失败，无法预订");
            }
            finally
            {
                selfLoading.Stop();
            }
        }

        #region 创建订单

        void ClearCreatePage()
        {
            DeviceKeyTB.Text = string.Empty;
            OrderShowList1.ItemsSource = null;
            OrderShowList2.ItemsSource = null;
        }
        readonly int ShowListPageSize = 8;
        int _showListPageIndex = 0;

        int showReady = 1;

        public int ShowListPageIndex
        {
            get { return _showListPageIndex; }
            set 
            {
                if (string.IsNullOrEmpty(App.CurrentUser.Address)
               || string.IsNullOrEmpty(App.CurrentUser.ChannelTel)
               || string.IsNullOrEmpty(App.CurrentUser.Chief)
               || string.IsNullOrEmpty(App.CurrentUser.Postcode))
                {
                    App.MessageBox.ShowDialog("请先在[渠道风采]中完善渠道基础信息");
                    return;
                }
                lock (this)
                {
                    if (_showListPageIndex != value && showReady >= 1 )
                    {

                        if (ProviderCBox.SelectedItem == null)
                        {
                            App.MessageBox.ShowDialog("请选择一个供应商");
                            return;
                        }

                        _showListPageIndex = value;

                        ShowPageIndexTB.Text = value.ToString();

                        PSSService.GetDeviceAsync(
                           (short)( App.GetID( ProviderCBox.SelectionBoxItem.ToString())),
                            DeviceKeyTB.Text, (ShowListPageIndex - 1) * ShowListPageSize, ShowListPageSize);
                        

                        ListLoading1.Show();
                        ListLoading2.Show();
                        OrderShowList2.ItemsSource = null;
                        OrderShowList1.ItemsSource = null;
                        showReady = 0;

                    } 
                }
            }
        }

       private void ProviderCBox_DropDownOpened(object sender, EventArgs e)
        {
            lock (this)
            {

                if ( CurrentOrderEnity != null)
                {
                    ProviderCBox.IsDropDownOpen = false;
                    App.MessageBox.ShowDialog("当前有未提交的订单，不允许更改供应商",
                        Title.Information);
                }
            }
            
        }
        

        private void OrderSearchBtn_Click(object sender, RoutedEventArgs e)
        {
            _showListPageIndex = 0;
            ShowListPageIndex = 1;

        }

        void PSSService_GetDeviceCompleted(object sender, GetDeviceCompletedEventArgs e)
        {
            try
            {
                lock (this)
                {

                    if (e.Result == null)
                    {
                        App.MessageBox.ShowDialog("查询失败，请稍后再试");
                    }
                    else if (e.Result.Count == 0)
                    {
                        if (e.UserState.Equals(1))
                        {
                            App.MessageBox.ShowDialog("没有查询到数据");
                        }
                    }
                    else
                    {
                        foreach (VW_PSS_DeviceInfo d in e.Result)
                        {
                            d.Picture_Path = (new Uri(HtmlPage.Document.DocumentUri, new Uri(d.Picture_Path, UriKind.Relative))).ToString();
                        }

                        if (e.Result.Count > ShowListPageSize / 2)
                        {
                            OrderShowList1.ItemsSource = e.Result.Take(ShowListPageSize / 2).ToList();
                            OrderShowList2.ItemsSource = e.Result.Skip(ShowListPageSize / 2).Take(ShowListPageSize / 2).ToList();
                        }
                        else
                        {
                            OrderShowList1.ItemsSource = e.Result;
                        }
                    }
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("查询失败，请稍后再试");
            }
            finally
            {
                ListLoading1.Stop();

                ListLoading2.Stop();

                showReady++;
            }
        }

        /// <summary>
        /// 前一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ShowListPageIndex > 1) ShowListPageIndex--;
        }

        /// <summary>
        /// 后一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBlock_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            if ((OrderShowList2.ItemsSource as List<VW_PSS_DeviceInfo>).Count == ShowListPageSize/2)
            {
                ShowListPageIndex++;
            }
        }

        private void ShowPageGoBtn_Click(object sender, RoutedEventArgs e)
        {
            int index = 0;
            if (int.TryParse(ShowPageIndexTB.Text, out index))
            {
                ShowListPageIndex = index;
            }
            else
            {
                ShowPageIndexTB.Text = ShowListPageIndex.ToString() ;
            }
        }
       
        /// <summary>
        /// ShowList1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {
            try
            {
                Point point = e.GetPosition(CreatePage);
                int colIndex = 1;
                if (point.X > 350) colIndex = 0;

                ShowBigImage.SetValue(Grid.ColumnProperty, colIndex);
                ShowBigImage.Visibility = Visibility.Visible;
                (ShowBigImage.Child as Image).Source = (sender as Image).Source;
            }
            catch 
            {
            }
        }

        /// <summary>
        /// ShowList1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseLeave(object sender, MouseEventArgs e)
        {
            ShowBigImage.Visibility = Visibility.Collapsed;
            (ShowBigImage.Child as Image).Source = null;
        }

        
        /// <summary>
        /// 显示添加到订单页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddOrder_MouseLeftButtonDown1(object sender, MouseButtonEventArgs e)
        {
            int id = int.Parse((sender as TextBlock).Tag.ToString());
            if (CurrentOrderEnity!=null && CurrentOrderEnity.IsOrdered(id))
            {
                App.MessageBox.ShowDialog("您已经预订了此终端，请先从订单中删除");
                return;
            }
            ShowDeviceTotalPanel(OrderShowList1, id);
        }

        void ShowDeviceTotalPanel(ListBox list,int deviceID)
        {
            try
            {
                VW_PSS_DeviceInfo deivce = null;
                foreach (VW_PSS_DeviceInfo d in (list.ItemsSource as List<VW_PSS_DeviceInfo>))
                {
                    if (d.Device_ID == deviceID)
                    {
                        deivce = d;
                        break;
                    }
                }
                OrderDeviceNameTB.Text = deivce.Device_Name;
                OrderDeviceNameTB.Tag = deivce;

                FeePackCBox.SelectedIndex = 0;
                DeviceTotalPanel.Visibility = Visibility.Visible;

                OrderTotalTB.Text = string.Empty;
                FeePackCBox.SelectedIndex = 0;
                OrderDeviceRemarkTB.Text = string.Empty;
            }
            catch
            {

                App.MessageBox.ShowDialog("获取终端数据失败，请稍后再试");
            }
        }


        /// <summary>
        /// 显示添加到订单页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddOrder_MouseLeftButtonDown2(object sender, MouseButtonEventArgs e)
        {
            int id=int.Parse((sender as TextBlock).Tag.ToString());
            if (CurrentOrderEnity != null && CurrentOrderEnity.IsOrdered(id))
            {
                App.MessageBox.ShowDialog("您已经预订了此终端，请先从订单中删除");
                return;
            }
            ShowDeviceTotalPanel(OrderShowList2, id);
        }


        private PSSOrderEnity CurrentOrderEnity = null;

        /// <summary>
        /// 设置预订的量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceTotalOKBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ProviderCBox.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请不要更改供应商");
            }
            if (CurrentOrderEnity == null)
            {
                CurrentOrderEnity = new PSSOrderEnity();

                CurrentOrderEnity.OrderChannel = string.Format("[{0}]{1}", App.CurrentUser.ChannelID, App.CurrentUser.ChannelName);

                CurrentOrderEnity.Address = App.CurrentUser.Address;

                CurrentOrderEnity.Chief = App.CurrentUser.Chief;
                CurrentOrderEnity.Tel = App.CurrentUser.ChannelTel;
                CurrentOrderEnity.Postcode = App.CurrentUser.Postcode;

                CurrentOrderEnity.CreateID = App.CurrentUser.UserID;

                CurrentOrderEnity.ProviderID=(short)(App.GetID(ProviderCBox.SelectionBoxItem.ToString()));
            }
            VW_PSS_DeviceInfo device = (OrderDeviceNameTB.Tag as VW_PSS_DeviceInfo);

            if (CurrentOrderEnity.IsOrdered(device.Device_ID))
            {
                App.MessageBox.ShowDialog("您已经预订了此终端，请先从订单中删除");
                return;
            }

        //    App.MessageBox.ShowDialog("是否要预订此终端?", new Action(DoOrder), Title.Information);
        //}
        //void DoOrder()
        //{

            try
            {
                int t = 0;
                if (!int.TryParse(OrderTotalTB.Text, out t))
                {

                    App.MessageBox.ShowDialog("预订量必须为整数");
                    return;
                }
                if (t < 1)
                {
                    App.MessageBox.ShowDialog("预订量不能小于1");
                    return;
                }


               int result= CurrentOrderEnity.AddDevice(
                    new OrderDeviceEnity
                    {
                        DeviceID = device.Device_ID,
                        DeviceName = device.Device_Name,
                        Price = device.Price.Value ,
                        Total = t,
                        FeePack = int.Parse(FeePackCBox.SelectionBoxItem.ToString()),
                        Remark = OrderDeviceRemarkTB.Text.Trim()
                    });
               if (result == 0)
               {
                   DeviceTotalPanel.Visibility = Visibility.Collapsed;
               }
               else
               {
                   App.MessageBox.ShowDialog("您已经预订了此终端，请先从订单中删除");
               }
            }
            catch
            {
                App.MessageBox.ShowDialog("添加预订信息失败，请稍后再试");
            }
        }
        /// <summary>
        /// 取消当前选择手机的预订
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceTotalCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            DeviceTotalPanel.Visibility = Visibility.Collapsed;
           
        }

        /// <summary>
        /// 清空当前订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClearOrderBtn0_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentOrderEnity == null)
            {
                App.MessageBox.ShowDialog("您还没有预订任何终端");
                return;
            }

            App.MessageBox.ShowDialog("是否要清空当前订单?", new Action(DoClearOrder), Title.Information);
        }
        void DoClearOrder()
        {
           
            CurrentOrderEnity.Dispose();
            CurrentOrderEnity = null;
        }

        /// <summary>
        /// 查看当前订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKBtn0_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentOrderEnity == null)
            {
                App.MessageBox.ShowDialog("您还没有预订任何终端");
                return;
            }

            ShowOrderDetail(CurrentOrderEnity);
        }

        private void ShowOrderDetail(PSSOrderEnity order)
        {
            if (OrderDetailPanel.Tag == null
                || !((OrderDetailPanel.Tag as PSSOrderEnity).OrderID.Equals(order.OrderID)))
            {
                OrderDetailPanel.Tag = order;

                OrderUserTB.Text = order.Chief;
                OrderTimeTB.Text = order.OrderTime.ToShortDateString() + " " + order.OrderTime.ToShortTimeString();
                OrderChannelTB.Text = order.OrderChannel;
                PCTB.Text = order.Postcode;
                TelTB.Text = order.Tel;
                AddressTB.Text = order.Address;

            }
            TotalConfirmTB.Text = order.TotalCount.ToString();
            TotalValueTB.Text = order.TotalValue.ToString("C");
            OrderShowGrid.ItemsSource = null;
            OrderShowGrid.ItemsSource = order.DeviceList;

            OrderConfirmBtn.IsEnabled = false;
            if (order.OrderID == -1
                && order.CreateID == App.CurrentUser.UserID)
            {
                //新增
                OrderConfirmBtn.IsEnabled = true;
            }
          //  else if(

            OrderDetailPanel.Visibility = Visibility.Visible;
        }



        private void CloseOrderDetail()
        {
            OrderDetailPanel.Visibility = Visibility.Collapsed;

        }

        #endregion


        #region 订单展示界面
        /// <summary>
        /// 关闭订单展示页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderConfirmBackBtn_Click(object sender, RoutedEventArgs e)
        {
            OrderDetailPanel.Visibility = Visibility.Collapsed;
        }

       
        

        /// <summary>
        /// 在当前订单中删除指定的终端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelDevice_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (OrderDetailPanel.Tag != null)
            {
                PSSOrderEnity order = (OrderDetailPanel.Tag as PSSOrderEnity);
                if (order.OrderStatus == -1)
                {// 渠道预订阶段
                    
                    CurrentOrderEnity.RemoveDevice((sender as TextBlock).Tag.ToString());
                    TotalConfirmTB.Text = CurrentOrderEnity.TotalCount.ToString();
                    TotalValueTB.Text = CurrentOrderEnity.TotalValue.ToString("C");
                }
            }
        }

    

        /// <summary>
        /// 确认提交此订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderConfirmBtn_Click(object sender, RoutedEventArgs e)
        {
            if (OrderDetailPanel.Tag != null)
            {
                PSSOrderEnity order = (OrderDetailPanel.Tag as PSSOrderEnity);
                if (order.DeviceList.Count == 0)
                {
                    App.MessageBox.ShowDialog("您还没有预订任何终端");
                    return;
                }
                if (order.OrderID == -1)
                {
                    //新增订单
                    OrderTitlePanel.Visibility = Visibility.Visible;
                    OrderConfirmBackBtn.IsEnabled = false;
                    OrderConfirmBtn.IsEnabled = false;
                }
                //else if (order.OrderStatus == 3)
                //{
                //    App.MessageBox.ShowDialog("请确认此订单已发货", new Action(DoConfirmOrder), Title.Information);
                //}
            }

        }
        ///// <summary>
        ///// 发货
        ///// </summary>
        //void DoConfirmOrder()
        //{


        //    OrderDetailPanel.Visibility = Visibility.Collapsed;
        //}

        /// <summary>
        /// 输入标题信息提交订单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderTitleOKBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(OrderTimeTB.Text))
            {
                App.MessageBox.ShowDialog("请输入订单标题");
                return;
            }

            App.MessageBox.ShowDialog("请确认提交此订单", new Action(DoSubmitOrder), Title.Information);

           
        }
        void DoSubmitOrder()
        {

            try
            {
                PSS_Order_List order = new PSS_Order_List
                    {
                        //Type_ID=1,
                        Create_ID = App.CurrentUser.UserID,
                        Subject = OrderTitleTB.Text,
                        Body = OrderBodyTB.Text,
                        Channel_ID=App.CurrentUser.ChannelID
                    };

                List<VW_OrderedDevice> deviceList = new List<VW_OrderedDevice>();
                foreach (OrderDeviceEnity e in CurrentOrderEnity.DeviceList)
                {
                    deviceList.Add(new VW_OrderedDevice
                    {
                        Device_IDk__BackingField = e.DeviceID,
                        Pricek__BackingField = (int)(e.Price * 100),
                        Totalk__BackingField = e.Total,
                        Fee_Packk__BackingField = (short)e.FeePack,
                        Remarkk__BackingField = e.Remark
                    });
                }


                PSSService.SubmitOrderAsync(order, deviceList,CurrentOrderEnity.ProviderID,true);
                

                TitleLoading.Show();
                OrderTitleOKBtn.IsEnabled = false;
                OrderTitleCancelBtn.IsEnabled = false;
            }
            catch 
            {
                App.MessageBox.ShowDialog("提交失败，请稍后再试");
            }
        }


        void PSSService_SubmitOrderCompleted(object sender, SubmitOrderCompletedEventArgs e)
        {
            try
            {
                OrderTitleOKBtn.IsEnabled = true;
                OrderTitleCancelBtn.IsEnabled = true;
                if (e.Result == 0 || e.Result==101 || e.Result==102)
                {

                    OrderTitlePanel.Visibility = Visibility.Collapsed;
                    OrderTitleTB.Text = string.Empty;
                    OrderBodyTB.Text = string.Empty;
                    OrderDetailPanel.Visibility = Visibility.Collapsed;
                    OrderConfirmBackBtn.IsEnabled = true;
                    OrderConfirmBtn.IsEnabled = true;

                    OrderTitleOKBtn.IsEnabled = true;
                    OrderTitleCancelBtn.IsEnabled = true;

                    CurrentOrderEnity.Dispose();
                    CurrentOrderEnity = null;
                    OrderDetailPanel.Tag = null;
                  
                    if (e.Result == 0)
                    {
                        App.MessageBox.ShowDialog("订单提交成功");
                    }
                    else
                    {
                        App.MessageBox.ShowDialog("订单提交成功,但发送提示邮件失败");
                    }
                }
                else
                {
                    App.MessageBox.ShowDialog("订单提交失败，请稍后再试");
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("订单提交失败，请稍后再试");
            }
            finally
            {

                TitleLoading.Stop();
            }
        }

        /// <summary>
        /// 返回订单详情界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderTitleCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            OrderTitlePanel.Visibility = Visibility.Collapsed;
            OrderTitleOKBtn.IsEnabled = true;
            OrderTitleCancelBtn.IsEnabled = true;
            OrderConfirmBackBtn.IsEnabled = true;
            OrderConfirmBtn.IsEnabled = true;

        }


        #endregion

        #region 串号管理界面

        /// <summary>
        /// 显示本页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IMEI_Click(object sender, RoutedEventArgs e)
        {
            PSSOrderEnity oe = (OrderDetailPanel.Tag as PSSOrderEnity);
            if (oe.OrderID == -1)
            {
                return;
            }

            IMEIPanel.Visibility = Visibility.Visible;
            if (IMEIPanel.Tag == null
                || !IMEIPanel.Tag.Equals(oe.OrderID))
            {

                ImeiGrid.ItemsSource = null;

                PSSService.GetIMEIByOrderIDAsync(oe.OrderID);

                IMEIPanel.Tag = oe.OrderID;
                imeiLoading.Show();
                IMEIOKBtn.IsEnabled = false;

            }
            if (oe.OrderStatus == 5 && oe.ProviderID== App.CurrentUser.ProviderID)
            {
                //发货状态
                IMEIDelBtn.Visibility = Visibility.Visible;
                IMEIOKBtn.Visibility = Visibility.Visible;

                IMEIChooseBtn.IsEnabled = true;
                IMEIOKBtn.IsEnabled = false;
              
                IMEIDelBtn.IsEnabled = true;
               

            }
            else
            {
                IMEIOKBtn.Visibility = Visibility.Collapsed;
                IMEIDelBtn.Visibility = Visibility.Collapsed;
                IMEIChooseBtn.IsEnabled = false;                
            }
        }

        static System.Text.RegularExpressions.Regex IMEIRegex = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]{15}$");

        /// <summary>
        /// 选择IMEI文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IMEIChooseBtn_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "txt|*.txt";
            dialog.Multiselect = false;
            try
            {
                if (dialog.ShowDialog().Value)
                {
                    IMEIFileTB.Text = dialog.File.Name;
                    List<VW_PSSOrderIMEI> imeiList = new List<VW_PSSOrderIMEI>();
                    PSSOrderEnity order = (OrderDetailPanel.Tag as PSSOrderEnity);
                    using (System.IO.StreamReader reader = dialog.File.OpenText())
                    {
                        while (!reader.EndOfStream)
                        {
                            string line = string.Empty;
                            line = reader.ReadLine();
                            if (string.IsNullOrEmpty(line))
                            {
                                continue;
                            }
                            string[] cols = line.Split(new char[] { '\t' });
                            int id = -1;
                            string name = string.Empty;
                            if (cols.Length != 2)
                            {
                                App.MessageBox.ShowDialog("每行都必须两列，以Tab键分隔:\r\n" + line);
                                return;
                            }
                            else
                            {
                                if (!int.TryParse(cols[0], out id))
                                {
                                    App.MessageBox.ShowDialog("终端编号必须是整数:\r\n" + cols[0]);
                                    return;
                                }
                                else if (!IMEIRegex.IsMatch(cols[1]))
                                {
                                    App.MessageBox.ShowDialog("串号必须是15位:\r\n" + cols[1]);
                                    return;
                                }
                            }

                            var iname =(from q in order.DeviceList
                                               where q.DeviceID == id
                                               select q.DeviceName);
                            if (iname.Any())
                            {
                                name = iname.Single();
                            }
                            else
                            {
                                App.MessageBox.ShowDialog("终端编号不属于本次预订中的终端:\r\n" + cols[0]);
                                return;
                            }
                            imeiList.Add(new VW_PSSOrderIMEI
                            {
                                Device_ID = id,
                                IMEI = cols[1],
                                Order_ID = order.OrderID,
                                Device_Name = name
                            });
                        }
                    }

                    if (imeiList.Count > 500)
                    {
                        App.MessageBox.ShowDialog("单次上传数据不能超过500行");
                        return;
                    }

                    var query = (from q in imeiList
                                 select q.IMEI).Distinct();
                    if (query.Count() < imeiList.Count())
                    {
                        App.MessageBox.ShowDialog("导入的串号存在重复，请核查");
                        return;
                    }

                    ImeiGrid.ItemsSource = imeiList;
                    IMEIOKBtn.IsEnabled = true;
                    IMEIDelBtn.IsEnabled = false;

                    App.MessageBox.ShowDialog("导入成功，共" + imeiList.Count.ToString() + "行");
                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("读取数据失败，" + ex.Message); ;
            }
        }

        /// <summary>
        /// 供应商提交串号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IMEIOKBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ImeiGrid.ItemsSource == null) return;
            App.MessageBox.ShowDialog("是否提交串号？", new Action(DoSubmitIMEI), Title.Information);
        
        }

        void DoSubmitIMEI()
        {
            try
            {
                List<VW_PSSOrderIMEI> iList = ImeiGrid.ItemsSource as List<VW_PSSOrderIMEI>;
                PSSService.InsertIMEIAsync(iList, App.CurrentUser.UserID);
                IMEIOKBtn.IsEnabled = false;
                IMEIChooseBtn.IsEnabled = false;
                imeiLoading.Show();
            }
            catch
            {

                App.MessageBox.ShowDialog("提交串号失败");
            }
            
        }

        /// <summary>
        /// 删除指定串号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IMEIDelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ImeiGrid.ItemsSource == null) return;
            if (ImeiGrid.SelectedItem == null) return;

            App.MessageBox.ShowDialog("是否删除此串号？", new Action(DoDelIMEI), Title.Information);
        }

        void DoDelIMEI()
        {
            try
            {
                PSSService.DeleteIMEIAsync((OrderDetailPanel.Tag as PSSOrderEnity).OrderID,
                       (ImeiGrid.SelectedItem as VW_PSSOrderIMEI).IMEI);
                IMEIDelBtn.IsEnabled = false;
                imeiLoading.Show();

            }
            catch 
            {
                App.MessageBox.ShowDialog("提交删除失败");
            }
        }

        /// <summary>
        /// 关闭本界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IMEICancelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (IMEIFileTB.Text != string.Empty)
            {
                IMEIFileTB.Text = string.Empty;
                ImeiGrid.ItemsSource = null;
            }

            IMEIPanel.Visibility = Visibility.Collapsed;
        }

        void PSSService_DeleteIMEICompleted(object sender, DeleteIMEICompletedEventArgs e)
        {
            try
            {
                if (e.Result)
                {
                    ImeiGrid.ItemsSource = null;
                    PSSService.GetIMEIByOrderIDAsync((OrderDetailPanel.Tag as PSSOrderEnity).OrderID);

                    App.MessageBox.ShowDialog("删除成功");
                }
                else
                {
                    imeiLoading.Stop();
                    App.MessageBox.ShowDialog("删除失败");

                }
            }
            catch 
            {
                imeiLoading.Stop();
                App.MessageBox.ShowDialog("删除失败");
            }
        
        }

        void PSSService_InsertIMEICompleted(object sender, InsertIMEICompletedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(e.Result))
                {
                    ImeiGrid.ItemsSource = null;
                    PSSService.GetIMEIByOrderIDAsync((OrderDetailPanel.Tag as PSSOrderEnity).OrderID);
                    App.MessageBox.ShowDialog("导入串号成功");
                }
                else
                {
                    imeiLoading.Stop();
                    App.MessageBox.ShowDialog("导入串号失败，" + e.Result);
                }
            }
            catch
            {

                imeiLoading.Stop();
                App.MessageBox.ShowDialog("导入串号失败，未知错误");
            }
            finally
            {
                IMEIChooseBtn.IsEnabled = true;

            }

        }

        void PSSService_GetIMEIByOrderIDCompleted(object sender, GetIMEIByOrderIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败");
                }
                else
                {
                    ImeiGrid.ItemsSource = e.Result;
                    IMEIDelBtn.IsEnabled = true;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("查询失败");
            }
            finally
            {
                imeiLoading.Stop();
                IMEIOKBtn.IsEnabled = false; 
                IMEIFileTB.Text = string.Empty;
            }
        }

        #endregion

        #region 订单查询界面

        void ClearListPage()
        {
            SubjectTB1.Text = string.Empty;
            CreaterIDTB1.Text = string.Empty;
            ListPageIndex = 0;
            StartDPicker.Text = DateTime.Today.ToShortDateString();
            EndDPicker.Text = StartDPicker.Text;

            ListGrid1.ItemsSource = null;

            
          //  ListProviderCBox.IsEnabled = App.CurrentUser.ProviderID == -1;
            if (App.CurrentUser.ProviderID == -1)
            {
                if (App.IsAuth(22))
                {
                    //管理员
                    CreaterIDTB1.Text = string.Empty;
                    CreaterIDTB1.IsReadOnly = false;
                }
                else
                {
                    CreaterIDTB1.Text = App.CurrentUser.UserID;
                    CreaterIDTB1.IsReadOnly = true;
                }
            }
            else
            {//供应商
                CreaterIDTB1.Text = string.Empty;
                CreaterIDTB1.IsReadOnly = false;

               
            }

        }

        readonly int ListPageSize = 10;
        private int _listPageIndex = 0;

        public int ListPageIndex
        {
            get { return _listPageIndex; }
            set
            {
                if (_listPageIndex == value) return;
                if (Loading1.Visibility == Visibility) return;

                _listPageIndex = value;

                ListPageIndexTB.Text = value.ToString();
                if (value == 0)
                {
                    ListGrid1.ItemsSource = null;
                }
                else
                {
                    if (ListProviderCBox.SelectedItem == null)
                    {
                        App.MessageBox.ShowDialog("请选择合适的供应商");
                        return;
                    }
                    try
                    {
                        DateTime start = DateTime.Parse(StartDPicker.Text + " 00:00:00");
                        DateTime end = DateTime.Parse(EndDPicker.Text + " 23:59:59");
                        PSSService.GetPSSOrderListAsync((short)(App.GetID(ListProviderCBox.SelectedItem.ToString())),
                            CreaterIDTB1.Text, SubjectTB1.Text, start, end, (value - 1) * ListPageSize, ListPageSize);
                        Loading1.Show();
                        ListGrid1.ItemsSource = null;
                    }
                    catch 
                    {
                        App.MessageBox.ShowDialog("提交查询失败，请稍后再试");
                    }
                }
            }
        }
        void PSSService_GetPSSOrderListCompleted(object sender, GetPSSOrderListCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询订单失败，请稍后再试");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");
                }
                else
                {
                    ListGrid1.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("查询订单失败，请稍后再试");
            }
            finally
            {
                Loading1.Stop();
                
            }
        }

        /// <summary>
        /// 输入工号或标题，订单查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKBtn1_Click(object sender, RoutedEventArgs e)
        {
            _listPageIndex = 0;
            ListPageIndex = 1;

        }

        private void ListPagePreBtn_Click(object sender, MouseButtonEventArgs e)
        {
            if (ListPageIndex > 1) ListPageIndex--;
        }

        private void ListPageNextBtn_Click(object sender, MouseButtonEventArgs e)
        {
            if (ListGrid1.ItemsSource != null
                && (ListGrid1.ItemsSource as List<VW_PSSOrderList>).Count == ListPageSize)
                ListPageIndex++;
        }
        private void ListPageGoBtn_Click(object sender, RoutedEventArgs e)
        {
            int index = -1;
            if (int.TryParse(ListPageIndexTB.Text, out index))
            {
                ListPageIndex = index;
            }
            else
            {
                ListPageIndexTB.Text = ListPageIndex.ToString();
            }
        }

        /// <summary>
        /// 查看订单处理流程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListOrderGrid_Click(object sender, MouseButtonEventArgs e)
        {
            TextBlock tb = sender as TextBlock;
            if (tb.Tag != null)
            {
                try
                {
                    InitStepPage(int.Parse(tb.Tag.ToString()));
                }
                catch
                {
                    App.MessageBox.ShowDialog("获取选中的ID失败");
                }
            }
        }

        int listOrderDetailStep = 2;
        /// <summary>
        /// 订单列表中查看订单详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListOrderDetail_Click(object sender, MouseButtonEventArgs e)
        {
           
            if (listOrderDetailStep >= 2)
            {
                int id = -1;
                if (int.TryParse((sender as TextBlock).Tag.ToString(), out id))
                {
                    if (SelectedOrderEnity == null
                        || SelectedOrderEnity.OrderID != id)
                    {
                       
                            SelectedOrderEnity = new PSSOrderEnity();
                       
                        try
                        {
                            PSSService.GetOrderUserDetailAsync(id);
                            PSSService.GetOrderDeviceDetailAsync(id);
                            listOrderDetailStep = 0;
                            SelectedOrderEnity.OrderID = id;
                            orderDetalLoading.Show();
                        }
                        catch
                        {
                            App.MessageBox.ShowDialog("获取订单编号失败");
                        }
                    }
                    else
                    {
                        ShowOrderDetail(SelectedOrderEnity);
                    }
                }
                else
                {
                    App.MessageBox.ShowDialog("获取订单编号失败");
                }
            }
        }
        PSSOrderEnity SelectedOrderEnity = null;
        void PSSService_GetOrderUserDetailCompleted(object sender, GetOrderUserDetailCompletedEventArgs e)
        {
            listOrderDetailStep++;
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取订单归属失败");

                }
                else
                {
                    SelectedOrderEnity.Address = e.Result.Address;
                    SelectedOrderEnity.Chief = e.Result.Chief;
                    SelectedOrderEnity.OrderChannel = string.Format("[{0}]{1}", e.Result.Channel_ID, e.Result.ChannelName);
                    SelectedOrderEnity.OrderStatus = e.Result.Status_ID;
                    SelectedOrderEnity.OrderTime = e.Result.Create_Time;
                    SelectedOrderEnity.Postcode = e.Result.Postcode;
                    SelectedOrderEnity.ProviderID = e.Result.Provider_ID;
                    SelectedOrderEnity.Tel = e.Result.Tel;


                    if (listOrderDetailStep == 2)
                    {
                        ShowOrderDetail(SelectedOrderEnity);
                    }
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取订单归属失败");
            }
            finally
            {
                if (listOrderDetailStep == 2)
                {
                    orderDetalLoading.Stop();
                }
            }
        }

        void PSSService_GetOrderDeviceDetailCompleted(object sender, GetOrderDeviceDetailCompletedEventArgs e)
        {
            listOrderDetailStep++;
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取订单终端列表失败");

                }
                else
                {
                    foreach (VW_PSSOrderDeviceDetail d in e.Result)
                    {
                        SelectedOrderEnity.AddDevice(new OrderDeviceEnity
                        {
                            DeviceID=d.Device_ID,
                            DeviceName=d.Device_Name,
                            FeePack=d.Fee_Pack,
                            Price=d.Price.Value,
                            Remark=d.Remark,
                            Total=d.Total
                        });
                    }


                    if (listOrderDetailStep == 2)
                    {
                        ShowOrderDetail(SelectedOrderEnity);
                    }
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取订单归属失败");
            }
            finally
            {
                if (listOrderDetailStep == 2)
                {
                    orderDetalLoading.Stop();
                }
            }
        }


        #endregion

        #region 工单流程

        private bool IsInforBoxIn = true;

        void ShowOrHideFlowPage()
        {
            if (!IsInforBoxIn)
            {

                PageOutSB.Begin();
                this.PageOutSB.Completed += (s, e) =>
                {
                    PageOutSB.Stop();
                    this.FlowPage.Visibility = Visibility.Collapsed;

                };
            }
            else
            {
                this.FlowPage.Visibility = Visibility.Visible;
                this.PageInSB.Begin();

            }

            IsInforBoxIn = !IsInforBoxIn;
        }

        int flowStep = 2;
        void InitStepPage(int WorkID)
        {
            lock (this)
            {
                //  this.FlowPage.Visibility = Visibility.Visible;
                ShowOrHideFlowPage();

                if (WorkID == -1)
                {
                    this.BodyTB2.Text = "请选择一个工单";
                    this.StepGrid.ItemsSource = null;
                }
                else
                {
                    if (flowStep != 2)
                    {
                        return;
                    }


                    //this.BodyTB2.Text = SelectedList.Subject;
                    try
                    {
                        //ServiceInstance.SupportSerivce.GetWorkStepCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);
                        //ServiceInstance.SupportSerivce.GetWorkBodyCompleted += new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);


                        PSSService.GetOrderBodyDAsync(WorkID);
                        PSSService.GetOrderStepByIDAsync(WorkID);
                        flowStep = 0;
                        this.FlowPage.Tag = WorkID;
                        this.flowLoading.Show();
                    }
                    catch
                    {
                        this.flowLoading.Stop();
                        this.FlowPage.Tag = null;
                        //ServiceInstance.SupportSerivce.GetWorkStepCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);
                        //ServiceInstance.SupportSerivce.GetWorkBodyCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);

                        App.MessageBox.ShowDialog("连接服务器失败");
                    }
                }
            }

        }
        void PSSService_GetOrderBodyDCompleted(object sender, GetOrderBodyDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    this.BodyTB2.Text = "获取数据失败";
                }
                else
                {
                    this.BodyTB2.Text = e.Result;
                }
            }
            catch
            {
                this.BodyTB2.Text = "获取数据失败";
            }
            finally
            {
                //ServiceInstance.SupportSerivce.GetWorkBodyCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkBodyCompletedEventArgs>(SupportSerivce_GetWorkBodyCompleted);
                flowStep++;
            }
        }

        void PSSService_GetOrderStepByIDCompleted(object sender, GetOrderStepByIDCompletedEventArgs e)
       
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取查询结果失败");
                }
                else
                {
                    StepGrid.ItemsSource = e.Result;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取查询结果失败");
            }
            finally
            {
                //ServiceInstance.SupportSerivce.GetWorkStepCompleted -= new EventHandler<SalaryChannel.SupportService.GetWorkStepCompletedEventArgs>(SupportSerivce_GetWorkStepCompleted);
                this.flowLoading.Stop();
                flowStep++;
            }
        }
        private void ReturnBtn_Click(object sender, RoutedEventArgs e)
        {
            //this.FlowPage.Visibility = Visibility.Collapsed;
            ShowOrHideFlowPage();
        }


        #endregion

        #region 待办工单
        void PSSService_GetMyWorkCompleted(object sender, GetMyWorkCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询待办工单失败");

                }
                else
                {
                    MyWorkListGrid.ItemsSource = e.Result;
                    MyWorkPage.Tag = App.CurrentUser.UserID;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("查询待办工单失败");


            }
            finally
            {
                RefreshBtn.IsEnabled = true;
                myWorkLoading.Stop();
            }
        }
        private void RefreshBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                PSSService.GetMyWorkAsync(App.CurrentUser.UserID);
                RefreshBtn.IsEnabled = false;
            }
            catch 
            {
                App.MessageBox.ShowDialog("查询待办工单失败");

            }
        }

        
        /// <summary>
        /// 显示处理界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DoMyWork_Click(object sender, MouseButtonEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前还有未完成的请求，请稍候");
                return;
            }
            try
            {

                RBtn1.IsChecked = true;
                OpinionTB.Text = string.Empty;
                NextUserCB4.SelectedIndex = -1;
                //Step_ID&Status_ID
                string[] tag = (sender as TextBlock).Tag.ToString().Split('&');
                ProcessGrid.Tag = tag[0];

                if ("13" == tag[1])
                {//渠道发货
                    PSSService.GetProviderDetailAsync(int.Parse(tag[0]));
                    myWorkLoading.Show();
                }
                else
                {
                    
                    ProcessGrid.Visibility = Visibility.Visible;
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("打开处理界面失败，请稍后再试");
            }
        }
        void PSSService_GetProviderDetailCompleted(object sender, GetProviderDetailCompletedEventArgs e)
        {
            try
            {
                if (e.Result == "-1")
                {
                    App.MessageBox.ShowDialog("当前步骤不存在或已经处理过了");
                }
                else if (e.Result == "-2")
                {
                    App.MessageBox.ShowDialog("当前订单不是退货发货状态");
                }
                else if (e.Result == "-3")
                {
                    App.MessageBox.ShowDialog("查询供应商地址失败，未知错误");
                }
                else
                {
                    App.MessageBox.ShowDialog("请确认所有手机终端已退货到以下地址：\r\n" + e.Result,
                        new Action(DoSendUnpurchase), Title.Information);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("查询供应商地址失败，未知错误");
            }
            finally
            {
                myWorkLoading.Stop();
            }
        }
        void DoSendUnpurchase()
        {
            ProcessGrid.Visibility = Visibility.Visible;
        }
        
        /// <summary>
        /// 提交处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OK4Btn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(OpinionTB.Text))
            {
                App.MessageBox.ShowDialog("请加注处理意见");
                return;
            }
            OrderDuration duration = OrderDuration.Next;
            string sendUser = string.Empty;
            if (RBtn2.IsChecked.Value)
            {
                if (NextUserCB4.SelectedItem == null)
                {
                    App.MessageBox.ShowDialog("请选择下一步处理人");
                    return;
                }
                duration = OrderDuration.Send;
                sendUser = App.GetID(NextUserCB4.SelectionBoxItem.ToString()).ToString();
            }
            else if (RBtn3.IsChecked.Value)
            {
                duration = OrderDuration.Rollback;

            }
            else if (RBtn4.IsChecked.Value)
            {
                duration = OrderDuration.Deny;
            }
            //else
            //{
            //    //完成，当状态=5，即发货时，需要检查串号是否录入
            //    //不能直接检查 PSSOrderEntity.IsIMEIReadey,因为只有点开订单详情界面，才会查询PSSOrderEntity
            //    //只在服务器中检查
                
            //}

            try
            {
                PSSService.DoMyWorkAsync(int.Parse(ProcessGrid.Tag.ToString()), OpinionTB.Text,
                        sendUser,
                        duration);
                OK4Btn.IsEnabled = false;
                Clear4Btn.IsEnabled = false;
                doWorkLoading.Show();
            }
            catch(Exception ex) 
            {
                App.MessageBox.ShowDialog("操作失败，"+ex.Message);
            }

        }

        void PSSService_DoMyWorkCompleted(object sender, DoMyWorkCompletedEventArgs e)
        {
            try
            {
                if (e.Result == 0
                    || e.Result ==101
                    || e.Result==102)
                {
                    OrderDetailPanel.Tag = null;
                    ProcessGrid.Tag = null;
                    OrderTitlePanel.Tag = null;

                    ProcessGrid.Visibility = Visibility.Collapsed;
                    RefreshBtn_Click(null, null);
                    if (e.Result == 0)
                    {

                        App.MessageBox.ShowDialog("操作成功");
                    }
                    else if (e.Result == 101)
                    {
                        App.MessageBox.ShowDialog("处理成功，但无法向接收人发送邮件提示");
                      
                    }
                    else if (e.Result == 102)
                    {
                        App.MessageBox.ShowDialog("处理成功，但发送提醒邮件失败");
                    }
                }
                else if (e.Result == 1)
                {
                    App.MessageBox.ShowDialog("开始步骤不允许回退");
                }
                else if (e.Result == 2)
                {
                    App.MessageBox.ShowDialog("不允许转派给自己");
                }
                else if (e.Result == 3)
                {
                    App.MessageBox.ShowDialog("未知的工单流向");
                }
              
                else if (e.Result == 4)
                {
                    App.MessageBox.ShowDialog("处理失败，此状态的订单不允许否决");
                }
                else if (e.Result == 5)
                {
                    App.MessageBox.ShowDialog("处理失败，只有创建人能否决审批");
                }
                else if (e.Result == 6)
                {
                    App.MessageBox.ShowDialog("处理失败，订单已经完成不能再处理");
                }else if (e.Result == 7)
                {
                    App.MessageBox.ShowDialog("处理失败，当前步骤已经处理过了，不能再处理");
                }
                else if (e.Result == 10)
                {
                    App.MessageBox.ShowDialog("处理失败，请检查串号是否录入完整");
                }
                else
                {
                    App.MessageBox.ShowDialog("处理失败，未知错误");
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("处理失败，未知错误");
            }
            finally
            {
                OK4Btn.IsEnabled = true;
                Clear4Btn.IsEnabled = true;

                doWorkLoading.Stop();
            }
        }


        /// <summary>
        /// 关闭显示界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Clear4Btn_Click(object sender, RoutedEventArgs e)
        {
            ProcessGrid.Visibility = Visibility.Collapsed;

        }


        /// <summary>
        /// 查询可转派人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RBtn2_Checked(object sender, RoutedEventArgs e)
        {
            if (RBtn2.IsChecked.Value)
            {
                try
                {
                    if (RBtn2.Tag == null
                               || !ProcessGrid.Tag.Equals(RBtn2.Tag))
                    {
                        NextUserCB4.ItemsSource = null;
                        RBtn2.Tag = ProcessGrid.Tag;

                        PSSService.GetAbleSendUsersAsync(int.Parse(RBtn2.Tag.ToString()),
                            App.CurrentUser.UserID);
                    }

                }
                catch 
                {
                    App.MessageBox.ShowDialog("查询可转派人失败");
                }
            }
        }

        void PSSService_GetAbleSendUsersCompleted(object sender, GetAbleSendUsersCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取可转派人失败");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有其他可转派人");
                }
                else
                {
                    NextUserCB4.ItemsSource = e.Result;
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("获取可转派人失败");
            }
        }


        #endregion

        #region 退货

        /// <summary>
        /// 校验串号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VerifyIMEIBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前还有未完成的请求，请稍候");
                return;
            }

            if (!IMEIRegex.IsMatch(UnpurIMEITB.Text))
            {
                App.MessageBox.ShowDialog("串号必须是15位整数");
                return;
            }
            var query = from q in CurrentUnpurIMEIList
                        where q.IMEI == UnpurIMEITB.Text
                        select q;
            if (query.Any())
            {
                App.MessageBox.ShowDialog("当前串号已经添加过了");
                return;
            }
            try
            {
               // PSSService.GetIMEIInfoAsync(UnpurIMEITB.Text,App.CurrentUser.ChannelID);
                unloading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("提交串号校验失败");
                
            }
        }
        static List<UnpurchaseIMEI> CurrentUnpurIMEIList = new List<UnpurchaseIMEI>();
       //void PSSService_GetIMEIInfoCompleted(object sender, GetIMEIInfoCompletedEventArgs e)
       // {
       //     try
       //     {
       //         if (e.Result == null)
       //         {
       //             App.MessageBox.ShowDialog("查询串号预订信息失败，无法退货");
       //         }
       //         else if (e.Result.IMEI == "-1")
       //         {
       //             App.MessageBox.ShowDialog("未预订过的终端不能退货");

       //         }
       //         else if (e.Result.IMEI == "-2")
       //         {
       //             App.MessageBox.ShowDialog("此终端已经是退货状态，不能再退货");

       //         }
       //         else
       //         {
       //             if (CurrentUnpurIMEIList.Count != 0)
       //             {
       //                 if (CurrentUnpurIMEIList[0].ProviderID != e.Result.ProviderID)
       //                 {
       //                     App.MessageBox.ShowDialog("此终端的供应商编号为"+e.Result.ProviderID.ToString()+"，与已添加的终端不一致，不能一起退货");
       //                     return;
       //                 }
       //             }

       //             CurrentUnpurIMEIList.Add(e.Result);
       //             UnpurIMEIGrid.ItemsSource = null;
       //             UnpurIMEIGrid.ItemsSource = CurrentUnpurIMEIList;
       //         }
       //     }
       //     catch
       //     {
       //         App.MessageBox.ShowDialog("查询串号预订信息失败，无法退货");
       //     }
       //     finally
       //     {
       //         unloading.Stop();
       //     }
       // }
       // /// <summary>
        /// 删除待退串号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelUnIMEIBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前还有未完成的请求，请稍候");
                return;
            }
            if (UnpurIMEIGrid.SelectedItem == null)
            {
                return;
            }

            try
            {
                CurrentUnpurIMEIList.Remove(UnpurIMEIGrid.SelectedItem as UnpurchaseIMEI);
                UnpurIMEIGrid.ItemsSource = null;
                UnpurIMEIGrid.ItemsSource = CurrentUnpurIMEIList;
            }
            catch 
            {
                App.MessageBox.ShowDialog("删除串号失败，请联系管理员");
            }
        }

        /// <summary>
        /// 提交退货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnSubmitBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前还有未完成的请求，请稍候");
                return;
            }
            if (string.IsNullOrEmpty(UnTitleTB.Text))
            {
                App.MessageBox.ShowDialog("请输入退货订单标题及原因");
                return;
            }
            if (CurrentUnpurIMEIList.Count==0)
            {
                App.MessageBox.ShowDialog("请输入退货终端的串号");
                return;
            }
            
            string msg =string.Format("您准备退货的终端共{0}台，价值{1}元。退货时必须在相同供应商[{2}]下预订价值不低于退货终端总价值的终端。是否提交？", CurrentUnpurIMEIList.Count,
                CurrentUnpurIMEIList.Sum(p=>p.Price),CurrentUnpurIMEIList[0].ProviderID);
         
            CurrentUnpurIMEIList.Sum(p => p.Price);
            App.MessageBox.ShowDialog(msg, new Action(DoSubmitUnpurchaseOrder), Title.Information);
        }

        void DoSubmitUnpurchaseOrder()
        {

            try
            {
                PSS_Order_List order = new PSS_Order_List
                {
                    //Type_ID=1,
                    Create_ID = App.CurrentUser.UserID,
                    Subject = UnTitleTB.Text,
                    Body = UnBodyTB.Text,
                    Channel_ID = App.CurrentUser.ChannelID
                };

                PSSService.SubmitUnpurchaseAsync(order, new List<UnpurchaseIMEI>( CurrentUnpurIMEIList));
                unloading.Show();
            }
            catch
            {
                App.MessageBox.ShowDialog("提交失败，请稍后再试");
            }
        }

        void PSSService_SubmitUnpurchaseCompleted(object sender, SubmitUnpurchaseCompletedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(e.Result))
                {
                    UnpurIMEITB.Text = string.Empty;
                    UnpurIMEIGrid.ItemsSource = null;

                    App.MessageBox.ShowDialog("提交成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("提交失败，" + e.Result);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("提交失败，未知错误");
            }
            finally
            {
                unloading.Stop();
            }
        }

        /// <summary>
        /// 清空当前界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnClearBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前还有未完成的请求，请稍候");
                return;
            }
            UnpurIMEITB.Text = string.Empty;
            UnpurIMEIGrid.ItemsSource = null;

        }

        #endregion

        #region 报表

        /// <summary>
        /// 提交报表查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReportSubBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }

            if (ReStartDP.SelectedDate.Value > ReEndDP.SelectedDate.Value)
            {
                App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                return;
            }
            if ( !App.IsAuth(1)
                && ReStartDP.SelectedDate.Value.AddMonths(1)< ReEndDP.SelectedDate.Value)
            {
                App.MessageBox.ShowDialog("统计时长不能超过1个月");
                return;
            }


            string start, end, cid;
            start = ReStartDP.SelectedDate.Value.ToString("yyyy-MM-dd 00:00:00");
            end = ReEndDP.SelectedDate.Value.ToString("yyyy-MM-dd 23:59:59");
            int pid = App.CurrentUser.ProviderID;
            
            cid = App.CurrentUser.ChannelID;
            if (pid != -1 )
            {
                cid = "-1";
            }
            if (App.IsAuth(22))
            {
                pid = -1;
            }
            if(App.IsAuth(13))
            {
                pid = -1;
                cid = "-1";
            }
           
            try
            {
                PSSService.GetReportByTableAsync(App.GetID(ReportNameCBox.SelectedItem.ToString()),
                       start, end, pid, cid, App.IsAuth(27) ? "-1" : App.CurrentUser.UserID);
                ReportLoading.Show();
                ReportSubBtn.IsEnabled = false;
                ReportExportBtn.IsEnabled = false;

                ReportGrid.ItemsSource = null;
                ReportDownBtn.Visibility = Visibility.Collapsed;
            }
            catch 
            {

                App.MessageBox.ShowDialog("连接服务失败");
            }

        }

        /// <summary>
        /// 导出报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReportExportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }

            if (ReStartDP.SelectedDate.Value > ReEndDP.SelectedDate.Value)
            {
                App.MessageBox.ShowDialog("开始日期不能大于结束日期");
                return;
            }
            if (!App.IsAuth(1)
                && ReStartDP.SelectedDate.Value.AddMonths(1) < ReEndDP.SelectedDate.Value)
            {
                App.MessageBox.ShowDialog("统计时长不能超过1个月");
                return;
            }


            string start, end, cid;
            start = ReStartDP.Text + " 00:00:00";
            end = ReEndDP.Text + " 23:59:59";
            int pid = App.CurrentUser.ProviderID;
            cid = App.CurrentUser.ChannelID;
            if (pid != -1)
            {
                cid = "-1";
            }
            if (App.IsAuth(22))
            {
                pid = -1;
            }
            if (App.IsAuth(13))
            {
                pid = -1;
                cid = "-1";
            }
            try
            {
                PSSService.GetReportByFileAsync(App.GetID(ReportNameCBox.SelectedItem.ToString()),
                    start, end, pid, cid,App.IsAuth(27)?"-1": App.CurrentUser.UserID);
                ReportLoading.Show();
                ReportSubBtn.IsEnabled = false;
                ReportExportBtn.IsEnabled = false;
                ReportDownBtn.NavigateUri = null;
                ReportGrid.ItemsSource = null;
                ReportDownBtn.Visibility = Visibility.Collapsed;
            }
            catch
            {

                App.MessageBox.ShowDialog("连接服务失败");
            }

        }


        void PSSService_GetReportByFileCompleted(object sender, GetReportByFileCompletedEventArgs e)
        {
            try
            {
                ReportLoading.Stop();
                ReportSubBtn.IsEnabled = true;
                ReportExportBtn.IsEnabled = true;
                if (e.Result == string.Empty)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");
                }
                else if ( e.Result == null||e.Result == "-1" )
                {
                    App.MessageBox.ShowDialog("导出失败，请联系管理员");
                }
                else
                {
                    //string uri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;

                    //if (uri.EndsWith("default.aspx"))
                    //{
                    //    uri = uri.Substring(0, uri.Length - ("default.aspx").Length);
                    //}

                    //uri += e.Result;

                    //ReportDownBtn.Tag = uri;

                    //ReportDownBtn.Visibility = Visibility.Visible;

                    if (Application.Current.IsRunningOutOfBrowser)
                    {

                        string u = PSSService.Endpoint.Address.Uri.AbsoluteUri.ToLower();

                        HyperlinkButton link = new HyperlinkButton();

                        if (u.EndsWith("pssservice.svc"))
                        {
                            u = u.Substring(0, u.Length - ("pssservice.svc").Length);
                        }
                        link.NavigateUri = new Uri(u + e.Result, UriKind.Absolute);
                        HyperlinkButtonAutomationPeer hyperlinkButtonAutomationPeer
                          = new HyperlinkButtonAutomationPeer(link);
                        hyperlinkButtonAutomationPeer.RaiseAutomationEvent
                        (AutomationEvents.InvokePatternOnInvoked);
                        IInvokeProvider iprovider = (IInvokeProvider)hyperlinkButtonAutomationPeer;

                        if (iprovider != null)
                            iprovider.Invoke();
                    }
                    else
                    {
                        string uri = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;

                        if (uri.EndsWith("default.aspx"))
                        {
                            uri = uri.Substring(0, uri.Length - ("default.aspx").Length);
                        }

                        uri += e.Result;

                        ReportDownBtn.NavigateUri = new Uri(uri);

                        ReportDownBtn.Visibility = Visibility.Visible;
                    }
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("导出异常，请从IE登录系统后导出数据," + ex.Message);
            }
        }

        void PSSService_GetReportByTableCompleted(object sender, GetReportByTableCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取报表失败");
                }
                else
                {
                    try
                    {
                        Silverlight.DataTable table = Xml2Table.Convert(e.Result.TableNamek__BackingField,
                                   e.Result._columns.ToList(), e.Result.XmlStringk__BackingField);
                        if (table.Rows.Count == 0)
                        {
                            App.MessageBox.ShowDialog("没有查询到数据");
                            ReportGrid.ItemsSource = null;
                            return;
                        }
                        ReportGrid.ItemsSource = table.GetBindableData(new Silverlight.Connector());

                    }
                    catch (Exception ex)
                    {
                        ReportGrid.ItemsSource = null;
                        App.MessageBox.ShowDialog("绑定数据失败，" + ex.Message);

                    }
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取报表失败");
            }
            finally
            {
                ReportLoading.Stop();
                ReportSubBtn.IsEnabled = true;
                ReportExportBtn.IsEnabled = true;

            }

        }

        void PSSService_GetAllPSSReportCompleted(object sender, GetAllPSSReportCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    ReportNameCBox.Items.Add("获取报表失败");
                }
                else
                {
                    foreach (var a in e.Result)
                    {
                        ReportNameCBox.Items.Add(a);
                    }
                }
            }
            catch 
            {
                ReportNameCBox.Items.Add("获取报表失败");
            }

        }
        #endregion

        #region 供应商信息维护

        void ClearProviderPage()
        {
            IsProviderHisCBox.IsChecked = false;
            ProGridRow1.SetValue(RowDefinition.HeightProperty, new GridLength(0));
            ProGridRow3.SetValue(RowDefinition.HeightProperty, new GridLength(180));
            ProviderSearchTB.Text = string.Empty;

            ProviderClearBtn_Click(null, null);
           
            ProHisStartDP.Text = DateTime.Today.ToShortDateString();
            ProHisEndDP.Text = ProHisStartDP.Text;

            ProviderNewBtn.IsEnabled = true;
            ProviderUpdateBtn.IsEnabled = false;
            ProviderSubmitBtn.IsEnabled = false;
            ProviderClearBtn.IsEnabled = false;

            ProviderMngGrid.ItemsSource = null;
        }

        private void IsProviderHisCBox_Checked(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未返回的请求，请稍后");
                return; 
            }
            if (IsProviderHisCBox.IsChecked.Value)
            {
                ProGridRow1.SetValue(RowDefinition.HeightProperty, new GridLength(30));
                ProGridRow3.SetValue(RowDefinition.HeightProperty,  new GridLength(0));
                ProviderMngGrid.AlternatingRowBackground =new SolidColorBrush( Colors.Red);
            }
            else
            {
                ProGridRow1.SetValue(RowDefinition.HeightProperty,  new GridLength(0));
                ProGridRow3.SetValue(RowDefinition.HeightProperty,  new GridLength(180));
                ProviderClearBtn_Click(null, null);
                ProviderMngGrid.AlternatingRowBackground = new SolidColorBrush(Colors.Gray);
            }
            ProviderMngGrid.ItemsSource = null;
        }
       
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProviderSearchBtn_Click(object sender, RoutedEventArgs e)
        {
            ProviderMngGrid.ItemsSource = null;
            try
            {
                if (IsProviderHisCBox.IsChecked.Value)
                {
                 //   PSSService.GetProviderHisAsync(ProviderSearchTB.Text);
                }
                else
                {
                    ProviderClearBtn_Click(null, null);
                    PSSService.GetProvderByNameAsync(ProviderSearchTB.Text.Trim());
                    
                }
                ProLoading.Show();
            }
            catch
            {
                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }
        }
        
        /// <summary>
        /// 选择供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProviderMngGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ProviderMngGrid.SelectedItem != null
                && !IsProviderHisCBox.IsChecked.Value)
            {
                PSS_Provider p = ProviderMngGrid.SelectedItem as PSS_Provider;
                ProviderNameTB.Text = p.Provider_Name;
                EnableCBox.SelectedIndex = p.Is_Enable == '1' ? 0 : 1;
                ChargerTB.Text = p.Person_In_Charge;
                ChargerUserTB.Text = p.User_ID;
                ProviderTelTB.Text = p.Tel;
                BankTB.Text = p.Bank;
                AccountNameTB.Text = p.Bank_Account_Name;
                AccountTB.Text = p.Bank_Account;
                PostcodeTB.Text = p.Postcode;
                ProviderAddressTB.Text = p.Address;
                RemarkTB.Text = p.Remark == null ? string.Empty : p.Remark; ;

                ProviderSubmitBtn.Tag = p.Provider_ID;

                SetProviderDetailReadOnly(true);

                ProviderNewBtn.IsEnabled = true;
                ProviderUpdateBtn.IsEnabled = true;
                ProviderSubmitBtn.IsEnabled = false;
                ProviderClearBtn.IsEnabled = false;
            }
        }
       
        /// <summary>
        /// 新增供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProviderNewBtn_Click(object sender, RoutedEventArgs e)
        {
            ProviderClearBtn_Click(null, null);

            SetProviderDetailReadOnly(false);

            ProviderSubmitBtn.Tag = null;

            ProviderNewBtn.IsEnabled = false;
            ProviderUpdateBtn.IsEnabled = false;
            ProviderSubmitBtn.IsEnabled = true;
            ProviderClearBtn.IsEnabled = true;
        }

        /// <summary>
        /// 更新供应商
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProviderUpdateBtn_Click(object sender, RoutedEventArgs e)
        {

            SetProviderDetailReadOnly(false);
            ProviderNewBtn.IsEnabled = false;
            ProviderUpdateBtn.IsEnabled = false;
            ProviderSubmitBtn.IsEnabled = true;
            ProviderClearBtn.IsEnabled = true;
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProviderSubmitBtn_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(ProviderNameTB.Text)
                 || EnableCBox.SelectedIndex < 0
                 || string.IsNullOrEmpty(ChargerTB.Text)
                 || string.IsNullOrEmpty(ChargerUserTB.Text)
                 || string.IsNullOrEmpty(ProviderTelTB.Text)
                 || string.IsNullOrEmpty(BankTB.Text)
                 || string.IsNullOrEmpty(AccountNameTB.Text)
                 || string.IsNullOrEmpty(AccountTB.Text)
                 || string.IsNullOrEmpty(PostcodeTB.Text)
                 || string.IsNullOrEmpty(ProviderAddressTB.Text)
                 //|| string.IsNullOrEmpty(RemarkTB.Text)
                )
            {
                App.MessageBox.ShowDialog("请完整填写以上各项信息");
                return;
            }
            App.MessageBox.ShowDialog("是否确认提交？", new Action(DoSubmitProvider), Title.Information);
        }
        void DoSubmitProvider()
        {
            PSS_Provider p = null;

            try
            {
                if (ProviderSubmitBtn.Tag != null)
                {
                    p = ProviderMngGrid.SelectedItem as PSS_Provider;
                    p.Update_ID = App.CurrentUser.UserID;

                }
                else
                {
                    p = new PSS_Provider();
                    p.Create_ID = App.CurrentUser.UserID;
                    p.Create_Time = DateTime.Now;

                }
                p.Provider_Name = ProviderNameTB.Text;
                p.Is_Enable = EnableCBox.SelectedIndex==0? '1':'0';
                p.Person_In_Charge = ChargerTB.Text;
                p.User_ID = ChargerUserTB.Text;
                p.Tel = ProviderTelTB.Text;
                p.Bank = BankTB.Text;
                p.Bank_Account_Name = AccountNameTB.Text;
                p.Bank_Account = AccountTB.Text;
                p.Postcode = PostcodeTB.Text;
                p.Address = ProviderAddressTB.Text;
                p.Remark = RemarkTB.Text;

                if (ProviderSubmitBtn.Tag != null)
                {
                    PSSService.UpdateProviderAsync(p);
                   
                }
                else
                {
                    PSSService.CreateProviderAsync(p);

                }
                ProLoading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败，请稍后再试");
            }
        }
        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProviderClearBtn_Click(object sender, RoutedEventArgs e)
        {
            ProviderNameTB.Text = string.Empty;
            EnableCBox.SelectedIndex = -1;
            ChargerTB.Text = string.Empty;
            ChargerUserTB.Text = string.Empty;
            ProviderTelTB.Text = string.Empty;
            BankTB.Text = string.Empty;
            AccountNameTB.Text = string.Empty;
            AccountTB.Text = string.Empty;
            PostcodeTB.Text = string.Empty;
            ProviderAddressTB.Text = string.Empty;
            RemarkTB.Text = string.Empty;

        }
        void SetProviderDetailReadOnly(bool value)
        {
            ProviderNameTB.IsReadOnly = value;
            EnableCBox.IsEnabled = !value;
            ChargerTB.IsReadOnly = value;
            ChargerUserTB.IsReadOnly = value;
            ProviderTelTB.IsReadOnly = value;
            BankTB.IsReadOnly = value;
            AccountNameTB.IsReadOnly = value;
            AccountTB.IsReadOnly = value;
            PostcodeTB.IsReadOnly = value;
            ProviderAddressTB.IsReadOnly = value;
            RemarkTB.IsReadOnly = value;
        }

       

        void PSSService_UpdateProviderCompleted(object sender, UpdateProviderCompletedEventArgs e)
        {
            try
            {
                if (e.Result == 0)
                {
                    SetProviderDetailReadOnly(true);
                    App.MessageBox.ShowDialog("操作成功");
                }
                else if (e.Result == 1)
                {
                    App.MessageBox.ShowDialog("供应商不存在，无法更新");
                }
                else if (e.Result == 2)
                {
                    App.MessageBox.ShowDialog("供应商名称重复，无法更新");
                }
                else
                {
                    App.MessageBox.ShowDialog("服务器异常，无法更新");
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("未知异常，无法更新");
            }
            finally
            {
                ProLoading.Stop();
            }
        }

        void PSSService_CreateProviderCompleted(object sender, CreateProviderCompletedEventArgs e)
        {
            try
            {
                if (e.Result == 0)
                {
                    SetProviderDetailReadOnly(true);
                    App.MessageBox.ShowDialog("操作成功");
                }
                
                else if (e.Result == 1)
                {
                    App.MessageBox.ShowDialog("供应商名称重复，无法创建");
                }
                else
                {
                    App.MessageBox.ShowDialog("服务器异常，无法创建");
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("未知异常，无法创建");
            }
            finally
            {
                ProLoading.Stop();
            }
        }

        void PSSService_GetProvderByNameCompleted(object sender, GetProvderByNameCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询供应商失败,服务器异常");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");
                }
                else
                {
                    ProviderMngGrid.ItemsSource = e.Result;
                    SetProviderDetailReadOnly(true);
                }

            }
            catch
            {

                App.MessageBox.ShowDialog("查询供应商失败,未知异常");
            }
            finally
            {
                ProLoading.Stop();
            }
        }
        

        #endregion

        #region 终端维护

        void ClearDeviceMng()
        {
            foreach (UIElement c in Mng_DeviceGrid.Children)
            {
                if(c.GetType().Equals(typeof( TextBox)))
                {
                    (c as TextBox).Text = string.Empty;
                }
                else if (c.GetType().Equals(typeof(ComboBox)))
                {
                    ComboBox com = c as ComboBox;
                    com.SelectedIndex = com.Items.Count > 0 ? 0 : -1;
                }
            }
        }

        void SetDeviceMngReadOnly(bool value)
        {
            foreach (UIElement c in Mng_DeviceGrid.Children)
            {
                
                if (c.GetType().Equals(typeof(TextBox)))
                {
                    TextBox tb = (c as TextBox);
                    if (tb.Tag != null && tb.Tag.ToString() == "ReadOnly")
                    {
                        continue;
                    }
                    tb.IsReadOnly = value;
                }
                else if (c.GetType().Equals(typeof(ComboBox)))
                {
                    ComboBox com = c as ComboBox;
                    if (com.Tag !=null && com.Tag.ToString() == "ReadOnly")
                    {
                        continue;
                    }
                    com.IsEnabled = !value;
                }
            }
        }
        private void Mng_DeviceListC_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int id = -1;
            id = App.GetID(Mng_DeviceListCB.SelectedText);
            if (id == -1)
            {
                //App.MessageBox.ShowDialog("请重新选择手机终端");
                return;
            }
            try
            {
                PSSService.GetDeviceDetailByIDAsync(id);
                Mng_DeviceLoading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("查询失败");

            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mng_NewDeviceBtn_Click(object sender, RoutedEventArgs e)
        {
            ClearDeviceMng();
            
            SetDeviceMngReadOnly(false);
            Mng_CmtDeviceBtn.Tag = null;

            Mng_NewDeviceBtn.IsEnabled = false;
            Mng_UpdateDeviceBtn.IsEnabled = false;
            Mng_CmtDeviceBtn.IsEnabled = true;
            Mng_DelDeviceBtn.IsEnabled = false;
            Mng_ClearDeviceBtn.IsEnabled = true;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mng_UpdateDeviceBtn_Click(object sender, RoutedEventArgs e)
        {
            SetDeviceMngReadOnly(false);
            Mng_CmtDeviceBtn.Tag = App.GetID(Mng_DeviceListCB.SelectedText);

            Mng_NewDeviceBtn.IsEnabled = false;
            Mng_UpdateDeviceBtn.IsEnabled = false;
            Mng_CmtDeviceBtn.IsEnabled = true;
            Mng_DelDeviceBtn.IsEnabled = false;
            Mng_ClearDeviceBtn.IsEnabled = true;
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mng_CmtDeviceBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求正在处理中，请稍候");
                return;
            }
            bool IsNull = false;
            foreach (UIElement c in Mng_DeviceGrid.Children)
            {
                
               
                if (c.GetType().Equals(typeof(TextBox)))
                {
                    TextBox tb = (c as TextBox);
                    if (tb.Tag != null && tb.Tag.ToString() == "NotNull")
                    {
                        if (string.IsNullOrWhiteSpace(tb.Text))
                        {
                            IsNull = true;
                            break;
                        }
                    }
                }
                else if (c.GetType().Equals(typeof(ComboBox)))
                {
                    ComboBox com = c as ComboBox;
                    if (com.Tag != null && com.Tag.ToString() == "NotNull")
                    {
                        if (com.SelectedIndex < 0)
                        {
                            IsNull = true;
                            break;
                        }
                    }
                }
            }
            if (IsNull)
            {
                App.MessageBox.ShowDialog("红色为必填项，不能为空");
                return;
            }
            App.MessageBox.ShowDialog("是否确认提交？", new Action(DoMng_CmtDeviceBtn_Click), Title.Warning);
        }
        void DoMng_CmtDeviceBtn_Click()
        {
            try
            {
                PSS_Device_Info device = null;
                if (Mng_CmtDeviceBtn.Tag == null)
                {
                    device = new PSS_Device_Info();
                    device.Create_Time = DateTime.Now;
                    device.Create_ID = App.CurrentUser.UserID;
                }
                else if (this.DevicePage.Tag != null)
                {
                    device = this.DevicePage.Tag as PSS_Device_Info;

                    device.Update_Time = DateTime.Now;
                    device.Update_ID = App.CurrentUser.UserID;
                }
                else
                {
                    this.Mng_DeviceListCB.SelectedIndex = -1;
                    App.MessageBox.ShowDialog("本地数据丢失，请重新查询再操作");
                    return;
                }
                device.Device_Name = Mng_DeviceNameTB.Text;
                device.Is_Enable = Mng_IsEnableCB.SelectedIndex == 0 ? '1': '0';
                device.Fac_Name = Mng_FacNameTB.Text;
                try
                {
                    device.Price = int.Parse(Mng_PriceTB.Text);
                    device.Stock_Price = int.Parse(Mng_StockPriceTB.Text);
                    device.Baojia_Duration = short.Parse(Mng_BaojiaTB.Text);
                    device.Return_Value = int.Parse(Mng_ReturnValueTB.Text);
                    device.Stock = int.Parse(Mng_StockTB.Text);
                }
                catch
                {
                    App.MessageBox.ShowDialog("整数项输入不合法");
                    return;
                }
                if (device.Stock_Price > device.Price)
                {
                    App.MessageBox.ShowDialog("最低限价不能高于售价");
                    return;
                }
                device.Picture_Path = Mng_PicTB.Text;
                device.Order_Total = 0;
                device.G3_Flag = Mng_TDCB.SelectedIndex == 0 ? '1' : '0';
                device.Smart_Flag = Mng_SmartCB.SelectedIndex == 0 ? '1' : '0';
                device.Baojia_Flag = Mng_BaojiaCB.SelectedIndex == 0 ? '1' : '0';


                device.BOSS_Fac_ID = Mng_BOSSDeviceTB.Text;
                device.BOSS_Device_ID = Mng_BOSSDeviceTB.Text;

                device.Remark = Mng_RemarkTB.Text;

                if (Mng_CmtDeviceBtn.Tag == null)
                {
                    PSSService.CreateDeviceAsync(new List<PSS_Device_Info>()
                    { 
                        device
                    });
                }
                else
                {
                    PSSService.UpdateDeviceAsync(device);
                }
                Mng_DeviceLoading.Show();
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("提交失败，" + ex.Message);
            }


        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mng_DelDeviceBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求存在处理中，请稍候");
                return;
            }
            if (string.IsNullOrWhiteSpace(Mng_DeviceListCB.SelectedText))
            {
                App.MessageBox.ShowDialog("请选择一个手机终端");
                return;
            }
            App.MessageBox.ShowDialog("是否确认删除此终端？", new Action(DoMng_DelDeviceBtn_Click), Title.Warning);
        }
        void DoMng_DelDeviceBtn_Click()
        {
            try
            {
                PSSService.DelDeviceAsync(App.GetID(Mng_DeviceListCB.SelectedText));
                Mng_DeviceLoading.Show();
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("提交失败，" + ex.Message);
            }
        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mng_ClearDeviceBtn_Click(object sender, RoutedEventArgs e)
        {
            ClearDeviceMng();
        }
        void PSSService_DelDeviceCompleted(object sender, DelDeviceCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    Mng_NewDeviceBtn.IsEnabled = true;
                    Mng_UpdateDeviceBtn.IsEnabled = true;
                    Mng_CmtDeviceBtn.IsEnabled = false;
                    Mng_DelDeviceBtn.IsEnabled = false;
                    Mng_ClearDeviceBtn.IsEnabled = false;
                    ClearDeviceMng();
                    App.MessageBox.ShowDialog("删除成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("删除失败，" + e.Result);
                }

            }
            catch
            {
                App.MessageBox.ShowDialog("删除失败，未知错误");
            }
            finally
            {
                Mng_DeviceLoading.Stop();
            }
        }

        void PSSService_UpdateDeviceCompleted(object sender, UpdateDeviceCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    Mng_NewDeviceBtn.IsEnabled = true;
                    Mng_UpdateDeviceBtn.IsEnabled = true;
                    Mng_CmtDeviceBtn.IsEnabled = false;
                    Mng_DelDeviceBtn.IsEnabled = true;
                    Mng_ClearDeviceBtn.IsEnabled = false;
                    SetDeviceMngReadOnly(true);
                    App.MessageBox.ShowDialog("更新成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("更新失败，" + e.Result);
                }
            }
            catch 
            {
                App.MessageBox.ShowDialog("更新失败，未知错误" );

            }
            finally
            {
                Mng_DeviceLoading.Stop();
            }
        }

        void PSSService_CreateDeviceCompleted(object sender, CreateDeviceCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    Mng_NewDeviceBtn.IsEnabled = true;
                    Mng_UpdateDeviceBtn.IsEnabled = true;
                    Mng_CmtDeviceBtn.IsEnabled = false;
                    Mng_DelDeviceBtn.IsEnabled = true;
                    Mng_ClearDeviceBtn.IsEnabled = false;
                    SetDeviceMngReadOnly(true);
                    App.MessageBox.ShowDialog("新增成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("新增失败，" + e.Result);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("新增失败，未知错误");

            }
            finally
            {
                Mng_DeviceLoading.Stop();
            }
        }

        void PSSService_GetDeviceDetailByIDCompleted(object sender, GetDeviceDetailByIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败，服务器异常");
                    return;
                }
                Mng_DeviceNameTB.Text = e.Result.Device_Name;
                Mng_IsEnableCB.SelectedIndex = e.Result.Is_Enable == '1' ? 0 : 1;
                Mng_FacNameTB.Text = e.Result.Fac_Name;
                Mng_PriceTB.Text = e.Result.Price.ToString();
                Mng_PicTB.Text = e.Result.Picture_Path == null ? string.Empty : e.Result.Picture_Path;

                Mng_TDCB.SelectedIndex = e.Result.G3_Flag == '1' ? 0 : 1;
                Mng_SmartCB.SelectedIndex = e.Result.Smart_Flag == '1' ? 0 : 1;
                Mng_BaojiaCB.SelectedIndex = e.Result.Baojia_Flag == '1' ? 0 : 1;
                Mng_BaojiaTB.Text = e.Result.Baojia_Duration == null ? "0" : e.Result.Baojia_Duration.ToString();
                Mng_ReturnValueTB.Text =  e.Result.Return_Value.ToString(); ;
                Mng_StockPriceTB.Text = e.Result.Stock_Price.ToString();
                Mng_StockTB.Text = e.Result.Stock == null ? "" : e.Result.Stock.ToString();
                Mng_BOSSFacTB.Text = e.Result.BOSS_Fac_ID;
                Mng_BOSSDeviceTB.Text = e.Result.BOSS_Device_ID;
                Mng_CreateTimeTB.Text = e.Result.Create_Time.ToShortDateString() + " " + e.Result.Create_Time.ToShortTimeString();
                Mng_CreaterTB.Text = e.Result.Create_ID;
                Mng_UpdateTimeTB.Text = e.Result.Update_Time == null ? "" : e.Result.Update_Time.Value.ToShortDateString() + " " + e.Result.Update_Time.Value.ToShortTimeString();
                Mng_UpdaterTB.Text = e.Result.Update_ID==null?"":e.Result.Update_ID;
                Mng_RemarkTB.Text = e.Result.Remark == null ? "" : e.Result.Remark;

                Mng_NewDeviceBtn.IsEnabled = true;
                Mng_UpdateDeviceBtn.IsEnabled = true;
                Mng_CmtDeviceBtn.IsEnabled = false;
                Mng_DelDeviceBtn.IsEnabled = true;
                Mng_ClearDeviceBtn.IsEnabled = false;
                SetDeviceMngReadOnly(true);

                this.DevicePage.Tag = e.Result;
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("解析结果异常，" + ex.Message);
            }
            finally
            {
                Mng_DeviceLoading.Stop();
            }
        }
        #endregion


        #region 供应商自销管理


        private void SelfTypeCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (SelfTypeCB.SelectedItem == null) return;
            if (SelfDataGrid.ItemsSource != null)
            {
                SelfDataGrid.ItemsSource = null;
            }

           SelfStoreProviderCB.Visibility= SelfStoreBtnSP.Visibility= SelfStoreSP.Visibility = SelfTypeCB.SelectedItem.ToString() =="入库" ? Visibility.Visible : Visibility.Collapsed;
           SelfSaleBtnSP.Visibility = SelfSaleSP.Visibility
               =UnSaleBtn.Visibility =ReprintBtn.Visibility
               = SelfTypeCB.SelectedItem.ToString() == "销售" ? Visibility.Visible : Visibility.Collapsed;

           SelfBillSP.Visibility = SelfTypeCB.SelectedItem.ToString() == "对账"? Visibility.Visible : Visibility.Collapsed;
           if (SelfStoreSP.Visibility == Visibility.Visible            
               )
           {
               try
               {
                   if (SelfProviderCB.Items.Count == 0)
                   {
                       PSSService.GetProviderAsync();
                       selfLoading.Show();

                   }
                   if (SelfDeviceNameCM.Items.Count == 0)
                   {
                       PSSService.Self_GetDeviceListByPIDAsync(false);
                       selfLoading.Show();
                   }
               }
               catch
               {
                   App.MessageBox.ShowDialog("发起获取供应商及终端信息失败");
               }
           }
        }

        #region 入库
        private void SelfProvidersssCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
            SelfDataGrid.ItemsSource = null;
        }

        void PSSService_Self_GetDeviceListByPIDCompleted(object sender, Self_GetDeviceListByPIDCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询供应商手机终端失败");
                }
                else
                {
                    SelfDeviceNameCM.Items.Clear();

                    foreach (string s in e.Result)
                    {
                        SelfDeviceNameCM.Items.Add(s);

                    }
                    if (DevicePage.Visibility == System.Windows.Visibility.Visible)
                    {
                        Mng_DeviceListCB.Items.Clear();
                        foreach (string s in e.Result)
                        {
                            Mng_DeviceListCB.Items.Add(s);
                        }
                    }
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("查询供应商手机终端失败");
            }
            finally
            {
                selfLoading.Stop();
            }
        }

        private void SelfIMEIAddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if (SelfDeviceNameCM.SelectedText == string.Empty)
            {
                App.MessageBox.ShowDialog("请先选定手机终端");
                return;
            }

            if (!IMEIRegex.IsMatch(SelfIMEI1AddTB.Text))
            {
                App.MessageBox.ShowDialog("输入串号1不合法！");
                SelfIMEI1AddTB.Text = string.Empty;
                Dispatcher.BeginInvoke(() => {
                    HtmlPage.Plugin.Focus();
                    SelfIMEI1AddTB.Focus();
                });
            }

            if (!IMEIRegex.IsMatch(SelfIMEI2AddTB.Text))
            {
                App.MessageBox.ShowDialog("输入串号2不合法！");
                SelfIMEI2AddTB.Text = string.Empty;
                Dispatcher.BeginInvoke(() => {
                    HtmlPage.Plugin.Focus();
                    SelfIMEI2AddTB.Focus();
                });
            }
            if (!IMEIRegex.IsMatch(SelfIMEI3AddTB.Text))
            {
                App.MessageBox.ShowDialog("输入串号3不合法！");
                SelfIMEI3AddTB.Text = string.Empty;
                Dispatcher.BeginInvoke(() => {
                    HtmlPage.Plugin.Focus();
                    SelfIMEI3AddTB.Focus();
                });
                return;
            }
            if (SelfIMEI1AddTB.Text == SelfIMEI2AddTB.Text
                || SelfIMEI1AddTB.Text == SelfIMEI3AddTB.Text
                || SelfIMEI2AddTB.Text == SelfIMEI3AddTB.Text)
            {
                App.MessageBox.ShowDialog("请输入一组不同的串号！");
                return;
            }

            // List<VW_PSS_Self_Storage> newStorageList = SelfDataGrid.ItemsSource as List<VW_PSS_Self_Storage>;
            if (newStorageList.Count > 0)
            {
                int i = 0;
                for (; i < newStorageList.Count; i++)
                {
                    if (newStorageList[i].IMEI1 == SelfIMEI1AddTB.Text
                        || newStorageList[i].IMEI2 == SelfIMEI1AddTB.Text
                        || newStorageList[i].IMEI3 == SelfIMEI1AddTB.Text
                        || newStorageList[i].IMEI1 == SelfIMEI2AddTB.Text
                        || newStorageList[i].IMEI2 == SelfIMEI2AddTB.Text
                        || newStorageList[i].IMEI3 == SelfIMEI2AddTB.Text
                        || newStorageList[i].IMEI1 == SelfIMEI3AddTB.Text
                        || newStorageList[i].IMEI2 == SelfIMEI3AddTB.Text
                        || newStorageList[i].IMEI3 == SelfIMEI3AddTB.Text
                        ) break;
                }
                if (i < newStorageList.Count)
                {

                    App.MessageBox.ShowDialog("不允许重复录入串号");
                    SelfIMEI1AddTB.Text = string.Empty;
                    SelfIMEI2AddTB.Text = string.Empty;
                    SelfIMEI3AddTB.Text = string.Empty;
                    Dispatcher.BeginInvoke(() => {
                        HtmlPage.Plugin.Focus();
                        SelfIMEI1AddTB.Focus();
                    });
                    return;
                }
            }

            string selectedText = SelfDeviceNameCM.SelectedText;
            int id = App.GetID(selectedText);
            string name = selectedText.Substring(id.ToString().Length + 2);
            DateTime now = DateTime.Now;

            newStorageList.Add(
                new VW_PSS_Self_Storage
                {
                    ID = newStorageList.Count + 1,
                    IMEI1 = SelfIMEI1AddTB.Text,
                    IMEI2 = SelfIMEI2AddTB.Text,
                    IMEI3 = SelfIMEI3AddTB.Text,
                    Device_ID = id,
                    Device_Name = name,
                    Store_Time = now

                });
            SelfDataGrid.ItemsSource = null;
            SelfDataGrid.ItemsSource = newStorageList;
            SelfDataGrid.UpdateLayout();
            SelfDataGrid.ScrollIntoView(newStorageList.Last(), SelfDataGrid.Columns[0]);
            SelfIMEI1AddTB.Text = string.Empty;
            SelfIMEI2AddTB.Text = string.Empty;
            SelfIMEI3AddTB.Text = string.Empty;
            SelfIMEI1AddTB.Focus();
        }

        static List< VW_PSS_Self_Storage> newStorageList = new List<VW_PSS_Self_Storage>();

        private void SelfIMEI1AddTB_OnGotFocus(object sender, RoutedEventArgs e)
        {
            SelfIMEI1AddTB.SelectAll();
        }

        private void SelfIMEI2AddTB_OnGotFocus(object sender, RoutedEventArgs e)
        {
            SelfIMEI2AddTB.SelectAll();
        }

        private void SelfIMEI3AddTB_OnGotFocus(object sender, RoutedEventArgs e)
        {
            SelfIMEI3AddTB.SelectAll();
        }

        /// Regex IMEIRegex = new Regex(@"^[A-Za-z0-9]{15}$");
        /// <summary>
        /// IMEI校验
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelfIMEI1AddTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (SelfIMEI1AddTB.Text.Contains('*'))
                {
                    SelfIMEI1AddTB.Text= SelfIMEI1AddTB.Text.Replace("*","");
                }
                if (!IMEIRegex.IsMatch(SelfIMEI1AddTB.Text))
                {

                    App.MessageBox.ShowDialog("输入串号不合法！");
                    SelfIMEI1AddTB.Text = string.Empty;
                    Dispatcher.BeginInvoke(() => {
                        HtmlPage.Plugin.Focus();
                        SelfIMEI1AddTB.Focus();
                    });
                }
                else
                {
                    Dispatcher.BeginInvoke(() => {
                        HtmlPage.Plugin.Focus();
                        SelfIMEI2AddTB.Focus();
                    });
                }
            }
        }

        private void SelfIMEI2AddTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (SelfIMEI2AddTB.Text.Contains('*'))
                {
                    SelfIMEI2AddTB.Text = SelfIMEI2AddTB.Text.Replace("*", "");
                }
                if (!IMEIRegex.IsMatch(SelfIMEI2AddTB.Text))
                {

                    App.MessageBox.ShowDialog("输入串号不合法！");
                    SelfIMEI2AddTB.Text = string.Empty;
                    Dispatcher.BeginInvoke(() => {
                        HtmlPage.Plugin.Focus();
                        SelfIMEI2AddTB.Focus();
                    });
                }
                else
                {
                    Dispatcher.BeginInvoke(() => {
                        HtmlPage.Plugin.Focus();
                        SelfIMEI3AddTB.Focus();
                    });
                }
            }
        }


        private void SelfIMEI3AddTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (SelfIMEI3AddTB.Text.Contains('*'))
                {
                    SelfIMEI3AddTB.Text = SelfIMEI3AddTB.Text.Replace("*", "");
                }
                SelfIMEIAddBtn_Click(null, null);
            }
        }


        /// <summary>
        /// 提交入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelfStoreBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if (newStorageList.Count==0)
            {
                return;
            }
            App.MessageBox.ShowDialog("是否确认提交？", new Action(DoSelfStoreBtn_Click), Title.Warning);


        }
        void DoSelfStoreBtn_Click()
        {
            List<PSS_Self_Storage> st = new List<PSS_Self_Storage>();
            string pidname =  this.SelfProviderCB.SelectedText;
            short pid = (short)App.GetID(pidname);
           // string name = pidname.Substring(pid.ToString().Length + 2);

            foreach (var q in newStorageList)
            {
                st.Add(new PSS_Self_Storage
                {
                    Device_ID= q.Device_ID,
                    IMEI1 = q.IMEI1,
                    IMEI2 = q.IMEI2,
                    IMEI3 = q.IMEI3,
                     Store_User_ID= App.CurrentUser.UserID,
                     Provider_ID = pid,
                     Store_Channel_ID= App.CurrentUser.ChannelID
                });
            }
            
            try
            {
                PSSService.Self_AddStorageAsync(st);
                selfLoading.Show();
                
            }
            catch 
            {

                App.MessageBox.ShowDialog("提交失败，请稍后再试");
            }
        }

        /// <summary>
        /// 入库结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PSSService_Self_AddStorageCompleted(object sender, Self_AddStorageCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    newStorageList.Clear();
                    SelfDataGrid.ItemsSource = null;
                    App.MessageBox.ShowDialog("入库成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("入库失败，" + e.Result);
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("入库失败，未知错误");
            }
            finally
            {
                selfLoading.Stop();
                SelfIMEI1AddTB.Focus();
            }
        }

       /// <summary>
       /// 批量入库
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void SelftStoreImportBtn_Click(object sender, RoutedEventArgs e)
        {
            App.MessageBox.ShowDialog("请使用文本导入:供应商编号  终端编号  串号1 串号2 串号3，以Tab键分隔。单次导入数据不能超过100行",
                new Action(DoStoreImport), Title.Information);
        }

        void DoStoreImport()
        {
            OpenFileDialog dia = new OpenFileDialog();
            dia.Filter = "(文本文件)|*.txt";
            dia.Multiselect = false;
            try
            {

                if (dia.ShowDialog().Value)
                {
                    List<PSS_Self_Storage> list = new List<PSS_Self_Storage>();
                    using (StreamReader reader = dia.File.OpenText())
                    {
                        string line = string.Empty;
                        while (!reader.EndOfStream)
                        {
                            line = reader.ReadLine();
                            if (string.IsNullOrEmpty(line.Trim()))
                            {
                                continue;
                            }
                            string[] cols = line.Split(new char[] { '\t' });
                            if (cols.Length != 5
                                || !IMEIRegex.IsMatch(cols[2])
                                || !IMEIRegex.IsMatch(cols[3])
                                || !IMEIRegex.IsMatch(cols[4]))
                            {
                                App.MessageBox.ShowDialog(string.Format("导入数据不合法，请查看第{0}行", list.Count + 1));
                                return;
                            }
                            try
                            {
                                if (list.Count > 100)
                                {
                                    App.MessageBox.ShowDialog("单次导入数据不能超过100行");
                                    return;
                                }
                                list.Add(new PSS_Self_Storage
                                               {
                                                   Provider_ID = short.Parse(cols[0]),                                                   
                                                   Device_ID = Int32.Parse(cols[1]),
                                                   IMEI1 = cols[2],
                                                   IMEI2 = cols[3],
                                                    IMEI3 = cols[4],
                                                    Store_User_ID = App.CurrentUser.UserID,
                                                   Store_Channel_ID = App.CurrentUser.ChannelID
                                               });
                            }
                            catch
                            {
                                App.MessageBox.ShowDialog(string.Format("导入数据不合法，请查看第{0}行", list.Count + 1));
                                return;
                            }
                        }
                    }

                    if (list.Count > 0)
                    {
                        try
                        {
                            PSSService.Self_AddStorageAsync(new List<PSS_Self_Storage>(list));
                            selfLoading.Show();
                        }
                        catch 
                        {
                            App.MessageBox.ShowDialog("提交数据失败，请稍后再试");
                            
                        }
                    }

                }

            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("导入数据失败，"+ex.Message);
            }
        }
       

        //private void SelfDeviceNameCM_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    if (SelfDeviceNameCM.SelectedItem == null) return;

        //    SelfIMEIAddTB.Focus();
        //}

        /// <summary>
        /// 删除指定IMEI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelftStoreDelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }

            if (SelfDataGrid.SelectedItem==null) return;

            VW_PSS_Self_Storage s = SelfDataGrid.SelectedItem as VW_PSS_Self_Storage;

            if (SelfTypeCB.SelectedIndex == 1)
            {
                newStorageList.Remove(s);
                SelfDataGrid.ItemsSource = null;
                SelfDataGrid.ItemsSource = newStorageList;
            }
            else
            {
                var source = SelfDataGrid.ItemsSource as List<VW_PSS_Self_Storage>;
                source.Remove(s);
                SelfDataGrid.ItemsSource = null;
                SelfDataGrid.ItemsSource = source;
            }
            SelfDataGrid.UpdateLayout();
            SelfIMEI1AddTB.Focus();
        }

        /// <summary>
        /// 清空当前列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelftStoreClearBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if ( SelfDataGrid.ItemsSource == null) return;

            App.MessageBox.ShowDialog("是否清空当前列表？", new Action(DoSelfStoreClearBtn_Clik), Title.Warning);
        }
        void DoSelfStoreClearBtn_Clik()
        {
            newStorageList.Clear();
            SelfDataGrid.ItemsSource = null;
            TotalValueTB.Text = string.Empty;
            SelfIMEI1AddTB.Focus();
        }

        #endregion

        #region 销售
        /// <summary>
        /// 集团特惠活动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GroupTHBtn_Checked(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if(GroupTHBtn.IsChecked==true)
            {
                ClearGroupTH();
                GroupTHGrid.Visibility = System.Windows.Visibility.Visible;
            }
        }

        /// <summary>
        /// 结账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelfSaleBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }

            if (PayWayCM.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择付费方式");
                return;
            }
            SaleUserNumCanvas.Visibility = System.Windows.Visibility.Visible;
            SaleUserNumTB.Text = string.Empty;
            SaleUserNumTB.IsReadOnly = false;

            if(GroupTHBtn.IsChecked==true)
            {
                SaleUserNumTB.Text = GroupTHUserPhoneTB.Text;
                SaleUserNumTB.IsReadOnly = true;
            }
           
        }

        /// <summary>
        /// 确认用户信息界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserCSOKBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.PhoneRegex.IsMatch(SaleUserNumTB.Text))
            {

                App.MessageBox.ShowDialog("是否确认结账？", new Action(DoSelfSaleBtn_Click), Title.Warning);
                SaleUserNumCanvas.Visibility = System.Windows.Visibility.Collapsed;

            }
            else
            {
                App.MessageBox.ShowDialog("用户号码不合法");
            }
        }

        /// <summary>
        /// 取消用戶信息界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserCSCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            SaleUserNumCanvas.Visibility = System.Windows.Visibility.Collapsed;
        }


        void DoSelfSaleBtn_Click()
        {
            decimal dPrice = -1;
            if (!Decimal.TryParse(SelfSaleTotalValueTB.Text,out dPrice))
            {
                App.MessageBox.ShowDialog("输入的总计金额不合法！");
                return;
            }
            int price = (int)dPrice *100;

            List<VW_PSS_Self_Storage> list = SelfDataGrid.ItemsSource as List<VW_PSS_Self_Storage>;
            if (list != null && list.Count == 1)
            {
                if (list[0].Store_Channel_ID != App.CurrentUser.ChannelID)
                {
                    App.MessageBox.ShowDialog("不能销售其它营业厅入库的手机");
                    return;
                }

                if (GroupTHBtn.IsChecked == true
                    && GroupTHGrid.Tag.ToString()=="true")
                {
                    // do nothing
                }
                else
                {
                    if (!App.IsAuth(30))
                    {//最大优惠权限
                        float youhui = 1.0F;
                        if (App.IsAuth(31))
                        {
                            youhui = 0.9F;
                        }
                        else if (App.IsAuth(32))
                        {
                            youhui = 0.8F;
                        }
                        else if (App.IsAuth(33))
                        {
                            youhui = 0.7F;
                        }
                        else if (App.IsAuth(34))
                        {
                            youhui = 0.6F;
                        }
                        else if (App.IsAuth(35))
                        {
                            youhui = 0.5F;
                        }

                        if ((float)(list[0].Stock_Price.Value * 100) * youhui > (float)price)
                        {
                            App.MessageBox.ShowDialog("输入的销售价不能低于进货价");
                            return;
                        }
                    }
                }
                List<PSS_Self_Storage> plist = new List<PSS_Self_Storage>();
                plist.Add(new PSS_Self_Storage
                {
                    Device_ID=list[0].Device_ID,
                    IMEI1=list[0].IMEI1,
                    Sale_Price = price,
                    Sale_Time =DateTime.Now,
                    Sale_User_ID = App.CurrentUser.UserID,
                    Pay_Method_ID =(short) PayWayCM.SelectedIndex,
                    Serv_Number=SaleUserNumTB.Text,
                    Guide=GuideTB.Text
                });

                try
                {
                    PSSService.Self_PayAsync(plist,GroupTHUserPhoneTB.Text,
                        GroupTHGroupIDTB.Text,
                        GroupTHGroupNameTB.Text,
                        GroupTHCustManagerIDTB.Text );
                    selfLoading.Show();
                }
                catch 
                {
                    App.MessageBox.ShowDialog("提交结账操作失败");
                }

            }
            else
            {
                return;
            }

        }
        void PSSService_Self_PayCompleted(object sender, Self_PayCompletedEventArgs e)
        {

            try
            {
                if (e.Result.Message == string.Empty)
                {
                    GroupTHBtn.IsChecked = false;
                   /*
                  <TextBlock x:Name="Self_ContentTB"  
                                       TextWrapping="Wrap"
                                       ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                                       ScrollViewer.VerticalScrollBarVisibility="Auto" FontSize="10"
                                       Margin="5,10,10,0" Height="146" Width="170">
                                <Run Text="机型："></Run><Run x:Name="Print_DeviceName"></Run>
                                <LineBreak></LineBreak>
                                <Run Text="串号："></Run><Run x:Name="Print_IMEI"></Run>
                                 <LineBreak></LineBreak>
                                <Run Text="金额："></Run><Run x:Name="Print_Cash"></Run>
                                 <LineBreak></LineBreak>
                               
                                <Run Text="供应商："></Run><Run x:Name="Print_Provider"></Run>
                                 <LineBreak></LineBreak>
                                 <Run Text="收银："></Run><Run x:Name="Print_User"></Run>
                                 <LineBreak></LineBreak>
                                <Run Text="时间："></Run><Run x:Name="Print_Time"></Run>
                                <LineBreak></LineBreak>
                                <Run Text="**************************"></Run>
                                <LineBreak></LineBreak>
                                <LineBreak></LineBreak>
                                <Run Text="收讫凭据，妥善保管。若有遗失，概不补打！"></Run>
                            </TextBlock>
                    */
                   // App.MessageBox.ShowDialog("操作成功");
                    List<VW_PSS_Self_Storage> list = SelfDataGrid.ItemsSource as List<VW_PSS_Self_Storage>;

                    Self_ContentTB.Inlines.Clear();
                    Self_ContentTB.Inlines.Add(new Run { Text = "机型：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = string.Format("[{0}]{1}", list[0].Device_ID, list[0].Device_Name) });
                    Self_ContentTB.Inlines.Add(new LineBreak());
                    Self_ContentTB.Inlines.Add(new Run { Text = "串号：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = list[0].IMEI1 });
                    Self_ContentTB.Inlines.Add(new LineBreak());
                    Self_ContentTB.Inlines.Add(new Run { Text = "供应商：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = list[0].Provider_Name });
                    Self_ContentTB.Inlines.Add(new LineBreak());

                    Self_ContentTB.Inlines.Add(new Run { Text = "金额：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = float.Parse(SelfSaleTotalValueTB.Text).ToString("C") });
                    Self_ContentTB.Inlines.Add(new LineBreak());

                    Self_ContentTB.Inlines.Add(new Run { Text = "付费方式：" });
                    Self_ContentTB.Inlines.Add(new Run { Text =  PayWayCM.SelectedIndex==0 ?"现金":"刷卡" });
                    Self_ContentTB.Inlines.Add(new LineBreak());


                    Self_ContentTB.Inlines.Add(new Run { Text = string.Format("用户号码：{0}", SaleUserNumTB.Text) });


                    Self_ContentTB.Inlines.Add(new LineBreak());
                    Self_ContentTB.Inlines.Add(new Run { Text = "本次积分：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = ((int)(float.Parse(SelfSaleTotalValueTB.Text))).ToString() });
                    Self_ContentTB.Inlines.Add(new LineBreak());

                    Self_ContentTB.Inlines.Add(new Run { Text = "累计积分：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = e.Result.TotalScore.ToString() });
                    Self_ContentTB.Inlines.Add(new LineBreak());

                   // list[0].TotalScore = e.Result.TotalScore;
                    Self_ContentTB.Inlines.Add(new Run { Text = "收银：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = App.CurrentUser.UserID });
                    Self_ContentTB.Inlines.Add(new LineBreak());

                    Self_ContentTB.Inlines.Add(new Run { Text = "时间：" });
                    Self_ContentTB.Inlines.Add(new Run { Text = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() });
                    Self_ContentTB.Inlines.Add(new LineBreak());

                    Self_ContentTB.Inlines.Add(new Run { Text = "**************************" });
                    Self_ContentTB.Inlines.Add(new LineBreak());
                    Self_ContentTB.Inlines.Add(new LineBreak());


                    Self_ContentTB.Inlines.Add(new Run { Text = string.Format("购机积分有效期截止到{0}年12月31日，过期作废。",
                        DateTime.Today.Year+1) });
                    Self_ContentTB.Inlines.Add(new LineBreak());
                    Self_ContentTB.Inlines.Add(new Run { Text = "收讫凭据，妥善保管。若有遗失，概不补打！" });
                    PrintGrid.Tag = list[0];
                    PrintGrid.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    App.MessageBox.ShowDialog("操作失败，" + e.Result.Message);
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("操作失败，未知错误");
            }
            finally
            {
                selfLoading.Stop();
            }
        }

        
       /// <summary>
       /// 加入待售列表
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private void SelfIMEISaleAddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!IMEIRegex.IsMatch(this.SelfIMEISaleTB.Text))
            {

                App.MessageBox.ShowDialog("输入串号不合法！");
                SelfIMEISaleTB.Text = string.Empty;
                Dispatcher.BeginInvoke(() =>
                {
                    HtmlPage.Plugin.Focus();
                    SelfIMEISaleTB.Focus();
                });

                return;

            }

            List<VW_PSS_Self_Storage> list = SelfDataGrid.ItemsSource as List<VW_PSS_Self_Storage>;
            if (list != null && list.Count > 0)
            {
                SelfDataGrid.ItemsSource = null;
            }

           

            try
            {
                PSSService.Self_GetDeviceStorageInfoAsync(SelfIMEISaleTB.Text);
                selfLoading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("查询终端信息提交失败");
            }

        }
        void PSSService_Self_GetDeviceStorageInfoCompleted(object sender, Self_GetDeviceStorageInfoCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    if (e.Result.Count > 0)
                    {
                        SelfDataGrid.ItemsSource = e.Result;

                        if (App.IsAuthOnly(36))
                        {//按销售价一口价销售
                            SelfSaleTotalValueTB.Text =
                                (e.Result[0].Price.Value).ToString();
                        }
                        else
                        {
                            SelfSaleTotalValueTB.Text = string.Empty;
                        }
                    }                   

                }
                else
                {
                    App.MessageBox.ShowDialog("查询失败，请稍后再试");
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("查询失败，请稍后再试");
            }
            finally
            {
                selfLoading.Stop();
                SelfIMEISaleTB.Text = string.Empty;
            }

        }
        /// <summary>
        /// 校验待售IMEI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelfIMEISaleTB_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (SelfIMEISaleTB.Text.Contains('*'))
                {
                    SelfIMEISaleTB.Text = SelfIMEISaleTB.Text.Replace("*", "");
                }
                SelfIMEISaleAddBtn_Click(null, null);
            }
        }

        /// <summary>
        /// 退库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelfUnStoreBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if (SelfDataGrid.SelectedItem == null) return;

            App.MessageBox.ShowDialog("是否确认退库操作?", new Action(DoSelfUnStoreBtn_Click), Title.Warning);

        }
        void DoSelfUnStoreBtn_Click()
        {
            VW_PSS_Self_Storage selected = SelfDataGrid.SelectedItem as VW_PSS_Self_Storage;
            if (selected.Sale_Time == null)
            {
                //if (selected.Provider_ID != App.CurrentUser.ProviderID)
                //{
                //    App.MessageBox.ShowDialog("不能将其它供应商的终端退库");
                //    return;
                //}
                try
                {
                    PSSService.Self_UnStoreAsync(selected.IMEI1);
                    selfLoading.Show();
                }
                catch
                {
                    App.MessageBox.ShowDialog("提交退库操作失败");
                }
            }
            else
            {
                App.MessageBox.ShowDialog("已销售的终端不能退库");
            }
        }
        void PSSService_Self_UnStoreCompleted(object sender, Self_UnStoreCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    App.MessageBox.ShowDialog("退库成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("退库失败，" + e.Result);

                }
            }
            catch
            {
                App.MessageBox.ShowDialog("退库失败，未知错误");
            }
            finally
            {
                selfLoading.Stop();
            }
        }

       
       
        #endregion

        #region 打印

        void PrintBillPage()
        {
            foreach (VW_PSS_Bill b in (PrintGrid.Tag as List<VW_PSS_Bill>))
            {
                StackPanel sp = new StackPanel();
                sp.Background = new SolidColorBrush(Colors.White);
                sp.Width = 200;

                Image img = new Image();
                img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Images/cmcc.jpg", UriKind.RelativeOrAbsolute));
                img.Stretch = Stretch.Fill;
                img.Height = 50;
                img.Margin = new Thickness(0, 10, 10, 0);

                sp.Children.Add(img);

                TextBlock tb = new TextBlock();
                tb.FontSize = 10;
                tb.Margin = new Thickness(5, 10, 10, 0);
                tb.Width = 170;
                tb.TextWrapping = TextWrapping.Wrap;

                foreach (Inline i in Self_ContentTB.Inlines)
                {
                    if (i is LineBreak)
                    {
                        tb.Inlines.Add(new LineBreak());
                    }
                    else if (i is Run)
                    {
                        tb.Inlines.Add(new Run { Text = (i as Run).Text });
                    }
                }
             
                sp.Children.Add(tb);

                PrintDocument p = new PrintDocument();
                p.PrintPage += (s, pe) =>
                    {
                        pe.HasMorePages = false;
                        pe.PageVisual = sp;
                    };
                p.EndPrint += new EventHandler<EndPrintEventArgs>(document_EndPrint);
                if (App.Current.IsRunningOutOfBrowser)
                {
                    p.Print("终端销售", new PrinterFallbackSettings(), true);
                }
                else
                {
                    p.Print("终端销售");
                }
            }

        }
        bool IsReprint = false;
        private void Self_PrintBtn_Click(object sender, RoutedEventArgs e)
        {

            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }

            try
            {
                if (PrintGrid.Tag.GetType().Equals(typeof(VW_PSS_Self_Storage)))
                {
                    //VW_PSS_Self_Storage b = PrintGrid.Tag as VW_PSS_Self_Storage;
                    StackPanel sp = new StackPanel();   
                    sp.Background = new SolidColorBrush(Colors.White);
                    sp.Width = 200;

                    Image img = new Image();
                    img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Images/cmcc.jpg", UriKind.RelativeOrAbsolute));
                    img.Stretch = Stretch.Fill;
                    img.Height = 50;
                    img.Margin = new Thickness(0, 10, 10, 0);

                    sp.Children.Add(img);

                    TextBlock tb = new TextBlock();
                    tb.FontSize = 10;
                    tb.Margin = new Thickness(5, 10, 10, 0);
                    tb.Width = 170;
                    tb.TextWrapping = TextWrapping.Wrap;

                    if (IsReprint)
                    {
                        tb.Inlines.Add(new Run { Text = "此为补打小票" });
                        tb.Inlines.Add(new LineBreak());
                    }
                    foreach (Inline i in Self_ContentTB.Inlines)
                    {
                        if (i is LineBreak)
                        {
                            tb.Inlines.Add(new LineBreak());
                        }
                        else if (i is Run)
                        {
                            tb.Inlines.Add(new Run { Text = (i as Run).Text });
                        }
                    }
                 
                    sp.Children.Add(tb);

                    PrintDocument document = new PrintDocument();
                    document.PrintPage += (s, pe) =>
                        {
                            //打印两份
                            pe.HasMorePages = (s as PrintDocument).PrintedPageCount==0;
                            pe.PageVisual = sp;
                        };
                    document.EndPrint += new EventHandler<EndPrintEventArgs>(document_EndPrint);
                    
                    if (App.Current.IsRunningOutOfBrowser)
                    {
                        document.Print("终端销售打印", new PrinterFallbackSettings(), true);
                    }
                    else
                    {
                        document.Print("终端销售打印");
                    }

                    selfLoading.Show();
                }
                else if(PrintGrid.Tag.GetType().Equals(typeof(List<VW_PSS_Bill>)))
                {//对账
                    PrintBillPage();
                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("打印异常，" + ex.Message);
            }
            
        }
       // bool PrintAgain = true;
        void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            selfLoading.Stop();
            App.MessageBox.ShowDialog("是否打印成功?", new Action(EndPrint), Title.Information);
        }
        void EndPrint()
        {
            SelfDataGrid.ItemsSource = null;
            SelfSaleTotalValueTB.Text = string.Empty;
            PrintGrid.Visibility = System.Windows.Visibility.Collapsed;
            PrintGrid.Tag = null;
            if (IsReprint) IsReprint = false;
        }

     

        private void Self_PrintCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            PrintGrid.Visibility = System.Windows.Visibility.Collapsed;
            if (IsReprint) IsReprint = false;
        }

        #endregion

        /// <summary>
        /// 对账
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Self_BillBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }

            try
            {
                int day = SelfBillDatePicker.SelectedDate.Value.Year * 10000
                       + SelfBillDatePicker.SelectedDate.Value.Month * 100
                       + SelfBillDatePicker.SelectedDate.Value.Day;
                PSSService.Self_BillAsync(day);
                selfLoading.Show();
            }
            catch
            {
                App.MessageBox.ShowDialog("发起对账失败，请稍后再试");
            }
        }
        void PSSService_Self_BillCompleted(object sender, Self_BillCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("获取对账结果失败，请稍后再试");
                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有对账结果");
                }
                else
                {
                     Self_ContentTB.Inlines.Clear();
                    foreach (VW_PSS_Bill b in e.Result )
                    {
                        Self_ContentTB.Inlines.Add(new Run { Text = "对账日期：" + b.Sale_Day.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "供应商编号：" + b.Provider_ID.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "供应商：" + b.Provider_Name.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "销售数量：" + b.IMEI_Count.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "现金：" + b.Sale_Total_Cash.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "刷卡：" + b.Sale_Total_Card.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "总金额：" + b.Sale_Total.ToString() });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "供应商负责人签字：" });
                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new LineBreak());

                        Self_ContentTB.Inlines.Add(new Run { Text = "**************************" });
                        Self_ContentTB.Inlines.Add(new LineBreak());
                    }

                    
                    PrintGrid.Tag = e.Result;
                    PrintGrid.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch
            {
                App.MessageBox.ShowDialog("获取对账结果失败，请稍后再试");
            }
            finally
            {
                selfLoading.Stop();
            }

        }

        /// <summary>
        /// 撤单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UnSaleBtn_Click(object sender, RoutedEventArgs e)
        {
            if (SelfRemark.Text == string.Empty)
            {
                App.MessageBox.ShowDialog("请填写备注");
                return;
            }
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if (SelfDataGrid.ItemsSource == null)
            {
                return;
            }

            App.MessageBox.ShowDialog("是否确认撤单？", new Action(DoUnSale), Title.Warning);
           
               
                

          
        }
        void DoUnSale()
        {
            try
            {
                List<VW_PSS_Self_Storage> blist = (SelfDataGrid.ItemsSource as List<VW_PSS_Self_Storage>);//.First();
                VW_PSS_Self_Storage b = blist[0];
                if (b.Sale_Time == null)
                {
                    App.MessageBox.ShowDialog("该终端未销售，无法撤单");
                    return;
                }
                if (b.Sale_Time.Value.ToShortDateString()
                    != DateTime.Today.ToShortDateString())
                {
                    App.MessageBox.ShowDialog("只有当天销售的终端才可以撤单");
                    return;
                }
                PSSService.Self_UnSaleAsync(new PSS_Self_UnSale
                {
                    IMEI=b.IMEI1,
                    Sale_Price=(int)(b.Sale_Price*100),
                    Sale_Time= b.Sale_Time.Value,
                    Sale_User_ID=b.Sale_User_ID,
                    UnSale_User_ID = App.CurrentUser.UserID,
                    Remark = SelfRemark.Text
                });
                selfLoading.Show();
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("请求撤单失败，" + ex.Message);
            }

        }
        void PSSService_Self_UnSaleCompleted(object sender, Self_UnSaleCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    SelfRemark.Text = string.Empty;
                    App.MessageBox.ShowDialog("撤单成功");
                }
                else
                {
                    App.MessageBox.ShowDialog("撤单失败，" + e.Result);
                }
            }
            catch
            {

                App.MessageBox.ShowDialog("撤单失败，未知错误");
            }
            finally
            {

                selfLoading.Stop();
            }
        }
        /// <summary>
        /// 补打小票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReprintBtn_Click(object sender, RoutedEventArgs e)
        {
           
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前请求未结束，请稍等");
                return;
            }
            if (SelfDataGrid.ItemsSource == null)
            {
                return;
            }
            try
            {
                VW_PSS_Self_Storage b = (SelfDataGrid.ItemsSource as List <VW_PSS_Self_Storage>).First();
                if (b.Sale_Time == null)
                {
                    App.MessageBox.ShowDialog("该终端未销售，无法打印小票");
                    return;
                }
                Self_ContentTB.Inlines.Clear();
                Self_ContentTB.Inlines.Add(new Run { Text = "此为补打小票" });
                Self_ContentTB.Inlines.Add(new LineBreak());
                Self_ContentTB.Inlines.Add(new Run { Text = "机型：" });
                Self_ContentTB.Inlines.Add(new Run { Text = string.Format("[{0}]{1}", b.Device_ID, b.Device_Name) });
                Self_ContentTB.Inlines.Add(new LineBreak());
                Self_ContentTB.Inlines.Add(new Run { Text = "串号：" });
                Self_ContentTB.Inlines.Add(new Run { Text = b.IMEI1 });
                Self_ContentTB.Inlines.Add(new LineBreak());
                Self_ContentTB.Inlines.Add(new Run { Text = "供应商：" });
                Self_ContentTB.Inlines.Add(new Run { Text = b.Provider_Name });
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run { Text = "金额：" });
                Self_ContentTB.Inlines.Add(new Run { Text = "￥"+b.Sale_Price.ToString() });
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run { Text = "付费方式：" });
                Self_ContentTB.Inlines.Add(new Run { Text = b.Pay_Method_ID == 0 ? "现金" : "刷卡" });
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run { Text = string.Format("用户号码：{0}", b.Serv_Number) });
                Self_ContentTB.Inlines.Add(new LineBreak());


                Self_ContentTB.Inlines.Add(new Run { Text = "本次积分：" });
                Self_ContentTB.Inlines.Add(new Run { Text = ((int)(b.Sale_Price.Value)).ToString() });      
                Self_ContentTB.Inlines.Add(new LineBreak());

                //Self_ContentTB.Inlines.Add(new Run { Text = "累计积分：" });
                //Self_ContentTB.Inlines.Add(new Run { Text = b.TotalScore.ToString() });
                //Self_ContentTB.Inlines.Add(new LineBreak());



                Self_ContentTB.Inlines.Add(new Run { Text = "收银：" });
                Self_ContentTB.Inlines.Add(new Run { Text = b.Sale_User_ID });
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run { Text = "时间：" });
                Self_ContentTB.Inlines.Add(new Run { Text = b.Sale_Time.Value.ToShortDateString() + " " + b.Sale_Time.Value.ToShortTimeString() });
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run { Text = "**************************" });
                Self_ContentTB.Inlines.Add(new LineBreak());
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run
                {
                    Text = string.Format("购机积分有效期截止到{0}年12月31日，过期作废。",
                        DateTime.Today.Year + 1)
                });
                Self_ContentTB.Inlines.Add(new LineBreak());

                Self_ContentTB.Inlines.Add(new Run { Text = "收讫凭据，妥善保管。若有遗失，概不补打！" });
                PrintGrid.Tag = b;
                IsReprint = true;
                PrintGrid.Visibility = System.Windows.Visibility.Visible;

            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("补打失败，" + ex.Message);

            }
        }

        private void ReportDownBtn_Click(object sender, RoutedEventArgs e)
        {

            //string filename = ReportNameCBox.SelectedItem.ToString();
            //string serverfile = ReportDownBtn.Tag.ToString();

            //filename = filename.Substring(filename.IndexOf(']') + 1) + "_" + DateTime.Today.ToString("yyyyMMdd")
            //    + serverfile.Substring(serverfile.LastIndexOf('.'));
            //DownloadPage d = new DownloadPage(serverfile, filename);
            //d.Show();
            
            ////ReportDownBtn.Tag.ToString(), filename);

            if (App.Current.IsRunningOutOfBrowser)
            {
                try
                {
                    HyperlinkButton link = new HyperlinkButton();
                    link.NavigateUri = new Uri(ReportDownBtn.Tag.ToString(), UriKind.Absolute);
                    HyperlinkButtonAutomationPeer hyperlinkButtonAutomationPeer
                      = new HyperlinkButtonAutomationPeer(link);
                    hyperlinkButtonAutomationPeer.RaiseAutomationEvent
                    (AutomationEvents.InvokePatternOnInvoked);
                    IInvokeProvider iprovider = (IInvokeProvider)hyperlinkButtonAutomationPeer;

                    if (iprovider != null)
                        iprovider.Invoke();
                }
                catch
                {
                    App.MessageBox.ShowDialog("请从IE登录后下载");
                }
            }
        }
        

       
        //private void Self_BillPrintBtn_Click(object sender, RoutedEventArgs e)
        //{

        //}

        #endregion

        #region 积分兑换
            
        /// <summary>
        /// 查询积分历史
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void score_HisBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }
            if (!App.PhoneRegex.IsMatch(score_UserTB.Text))
            {
                App.MessageBox.ShowDialog("用户号码不合法");
                return;
            }
            try
            {
                PSSService.GetScoreHisAsync(score_UserTB.Text);
                score_HisDG.ItemsSource = null;
                score_TotalScoreTB.Text = string.Empty;
                score_Loading.Show();
            }
            catch
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }

        }
        void PSSService_GetScoreHisCompleted(object sender, GetScoreHisCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败，服务器异常");

                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");

                }
                else
                {
                    score_HisDG.ItemsSource = e.Result;
                    score_TotalScoreTB.Text = e.Result.Where(a => a.Create_Time.Year >= (DateTime.Now.Year - 1)).
                      Sum(s => s.Score).ToString();
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("查询失败，" + ex.Message);
            }
            finally
            {
                score_Loading.Stop();
            }
        }
        /// <summary>
        /// 查询可用礼品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void score_QueryGiftBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }
            try
            {
                PSSService.GetValidGiftAsync(score_NameQueryTB.Text);
                score_Loading.Show();
            }
            catch 
            {
                App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        void PSSService_GetGiftCompleted(object sender, GetValidGiftCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("查询失败，服务器异常");

                }
                else if (e.Result.Count == 0)
                {
                    App.MessageBox.ShowDialog("没有查询到数据");

                }
                else
                {
                   score_GiftDG.ItemsSource = e.Result;
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("查询失败，" + ex.Message);
            }
            finally
            {
                score_Loading.Stop();
            }
        }

        /// <summary>
        /// 兑换积分
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void score_GiftBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }

            if (!App.PhoneRegex.IsMatch(score_UserTB.Text))
            {
                App.MessageBox.ShowDialog("用户号码不合法");
                return;
            }
            if (score_GiftDG.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择一个礼品");
                return;
            }

            PSS_Score_Gift gift = score_GiftDG.SelectedItem as PSS_Score_Gift;

            int vscore = 0;
            if (!int.TryParse(score_TotalScoreTB.Text, out vscore))
            {
                App.MessageBox.ShowDialog("用户可用积分为零，请重新查询");
                return;
            }
            if (vscore < gift.Score)
            {
                App.MessageBox.ShowDialog("用户可用积分不足");
                return;
            }

            App.MessageBox.ShowDialog(string.Format("是否兑换【{0}】【{1}分】？", gift.Gift_Name, gift.Score),
                new Action(Doscore_GiftBtn_Click), Title.Information);

        }
        void Doscore_GiftBtn_Click()
        {
            try
            {
                PSSService.ExchangeScoreAsync(score_UserTB.Text,
                    (score_GiftDG.SelectedItem as PSS_Score_Gift).ID, App.CurrentUser.UserID);
                score_Loading.Show();
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("连接服务器失败，" + ex.Message);
            }

        }

        void PSSService_ExchangeScoreCompleted(object sender, ExchangeScoreCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("操作失败，服务器异常");

                }
                else if (e.Result== string.Empty)
                {
                    App.MessageBox.ShowDialog("操作成功，是否打印小票",new Action(DoScorePrint),Title.Information);

                   
                }
                else
                {
                    App.MessageBox.ShowDialog("操作失败，"+e.Result);
                }
            }
            catch (Exception ex)
            {

                App.MessageBox.ShowDialog("操作失败，" + ex.Message);
            }
            finally
            {
                score_Loading.Stop();
            }
        }
        void DoScorePrint()
        {
            //打印小票
            StackPanel sp = new StackPanel();
            sp.Background = new SolidColorBrush(Colors.White);
            sp.Width = 200;

            Image img = new Image();
            img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Images/cmcc.jpg", UriKind.RelativeOrAbsolute));
            img.Stretch = Stretch.Fill;
            img.Height = 50;
            img.Margin = new Thickness(0, 10, 10, 0);

            sp.Children.Add(img);

            TextBlock tb = new TextBlock();
            tb.FontSize = 10;
            tb.Margin = new Thickness(5, 10, 10, 0);
            tb.Width = 170;
            tb.TextWrapping = TextWrapping.Wrap;

            tb.Inlines.Add(new Run { Text = "**************************" });
            tb.Inlines.Add(new LineBreak());
            

            tb.Inlines.Add(new Run { Text = "用户号码：" + score_UserTB.Text });
            tb.Inlines.Add(new LineBreak());

            PSS_Score_Gift gift = score_GiftDG.SelectedItem as PSS_Score_Gift;
            tb.Inlines.Add(new Run { Text = "兑换礼品：" + gift.Gift_Name });
            tb.Inlines.Add(new LineBreak());
            tb.Inlines.Add(new Run { Text = "扣减积分：" + gift.Score.ToString() });
            tb.Inlines.Add(new LineBreak());

            tb.Inlines.Add(new Run { Text = "剩余积分：" + (int.Parse(score_TotalScoreTB.Text)-gift.Score).ToString() });
            tb.Inlines.Add(new LineBreak());

            tb.Inlines.Add(new Run { Text = "操作工号：" + App.CurrentUser.UserID });
            tb.Inlines.Add(new LineBreak());
            tb.Inlines.Add(new Run { Text = "兑换时间：" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() });
            tb.Inlines.Add(new LineBreak());

            tb.Inlines.Add(new Run { Text = "**************************" });
            tb.Inlines.Add(new LineBreak());
            tb.Inlines.Add(new Run { Text = "移动手机卖场积分兑换小票" });
            tb.Inlines.Add(new LineBreak());

            tb.Inlines.Add(new LineBreak());

            sp.Children.Add(tb);

            PrintDocument document = new PrintDocument();
            document.PrintPage += (s, pe) =>
            {
                //打印两份
                pe.HasMorePages = (s as PrintDocument).PrintedPageCount == 0;
                pe.PageVisual = sp;
            };
            document.EndPrint += new EventHandler<EndPrintEventArgs>(Scoredocument_EndPrint);

            if (App.Current.IsRunningOutOfBrowser)
            {
                document.Print("终端销售打印", new PrinterFallbackSettings(), true);
            }
            else
            {
                document.Print("终端销售打印");
            }

            selfLoading.Show();
        }
        void Scoredocument_EndPrint(object sender, EndPrintEventArgs e)
        {
            selfLoading.Stop();
           //App.MessageBox.ShowDialog("是否打印成功?", new Action(EndPrint), Title.Information);
        }
           /// <summary>
        /// 兑换积分撤单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void score_UnGiftBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }
            if (score_HisDG.SelectedItem == null)
            {
                App.MessageBox.ShowDialog("请选择一条积分兑换记录");
                return;
            }
            VW_PSS_Score_His shis = score_HisDG.SelectedItem as VW_PSS_Score_His;
            if (shis.Score >= 0)
            {
                App.MessageBox.ShowDialog("您选择的不是积分兑换记录，无法撤单");
                return;
            }
            App.MessageBox.ShowDialog(string.Format("是否将【{0}】积分兑换操作撤单？", shis.Gift_Name),
                new Action(Doscore_UnGiftBtn_Click), Title.Information);
        }
        void Doscore_UnGiftBtn_Click()
        {
            try
            {
                PSSService.UnExchangeScoreAsync((score_HisDG.SelectedItem as VW_PSS_Score_His).ID);
                score_Loading.Show();
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("提交失败，" + ex.Message);
            }
        }
        void PSSService_UnExchangeScoreCompleted(object sender, UnExchangeScoreCompletedEventArgs e)
        {
            try
            {
                if (e.Result == string.Empty)
                {
                    App.MessageBox.ShowDialog("撤单成功");
                }
                else if (e.Result == null)
                {
                    App.MessageBox.ShowDialog("撤单失败，服务器错误");
                }
                else
                {
                    App.MessageBox.ShowDialog(e.Result);
                }
            }
            catch (Exception ex)
            {
                App.MessageBox.ShowDialog("撤单失败，未知错误");
            }
            finally
            {
                score_Loading.Stop();
            }
        }
        #endregion

        #region 集团特惠活动
        static Random _thrand = new Random((int)DateTime.Now.Ticks);
        string _code = string.Empty;
        static DispatcherTimer _coderTimer = null;
        private void GroupTHSendVerifyCodeBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }
            if(GroupTHUserPhoneTB.Text == string.Empty
           || GroupTHGroupIDTB.Text == string.Empty
            ||GroupTHGroupNameTB.Text == string.Empty
            ||GroupTHCustManagerIDTB.Text == string.Empty)
            {
                App.MessageBox.ShowDialog("请填写除验证码外的信息");
                return;
            }
            if(!App.PhoneRegex.IsMatch(GroupTHUserPhoneTB.Text))
            {
                GroupTHInfoTB.Text = "用户号码不合法";
                return;
            }
            try
            {
                _code=_thrand.Next(100000, 999999).ToString();
                PSSService.GroupTHSendVerifyCodeAsync(GroupTHCustManagerIDTB.Text,
                       _code);
                THloading.Show();
                GroupTHInfoTB.Text = "已发送验证码，请查收邮件";

                if(_coderTimer == null)
                {
                    _coderTimer = new DispatcherTimer ();
                    _coderTimer.Tick += coderTimer_Tick;
                    _coderTimer.Interval = new TimeSpan(0,0,1);
                }
                GroupTHSendVerifyCodeBtn.IsEnabled = false;
                timerCount=0;
                _coderTimer.Start();
            }
            catch 
            {
                  App.MessageBox.ShowDialog("连接服务器失败");
            }
        }

        int timerCount = 0;
        readonly int timerCountMax=30;
        void coderTimer_Tick(object sender, EventArgs e)
        {
            if(timerCount==timerCountMax)
            {
                _coderTimer.Stop();
                GroupTHSendVerifyCodeBtn.IsEnabled = true;
                GroupTHSendVerifyCodeBtn.Content = "发送验证码";
            }
            else
            {
                timerCount++;
                GroupTHSendVerifyCodeBtn.Dispatcher.BeginInvoke(delegate(){
                    GroupTHSendVerifyCodeBtn.Content = string.Format("{0}秒后可发送", timerCountMax - timerCount);
                        });
            }

        }

       
        void PSSService_GroupTHSendVerifyCodeCompleted(object sender, GroupTHSendVerifyCodeCompletedEventArgs e)
        {
            if(e.Result=="-1")
            {
                GroupTHInfoTB.Text=("客户经理不存在");
            }
            else if(e.Result=="-2")
            {
                GroupTHInfoTB.Text = ("发送验证码失败");
            }
            else if(e.Result=="-3")
            {
                GroupTHInfoTB.Text="未知错误";

            }
            else
            {
                GroupTHCustManagerNameTB.Text = e.Result;
            }
            THloading.Stop();
        }


        private void GroupTHVerifyBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }
            if (_code == GroupTHVerfyCodeTB.Text
                && !string.IsNullOrEmpty(GroupTHVerfyCodeTB.Text))
            {
                GroupTHGrid.Tag = "true";
                GroupTHInfoTB.Text="验证通过";
            }
            else
            {
                GroupTHInfoTB.Text = "验证码错误";
            }
        }

        private void GroupTHCancelBtn_Click(object sender, RoutedEventArgs e)
        {
            if (App.IsRunning)
            {
                App.MessageBox.ShowDialog("当前有未完成的请求，请稍候");
                return;
            }
            if (GroupTHGrid.Tag.ToString()!="true")
            {
                GroupTHBtn.IsChecked = false;
            }
            if (_coderTimer!=null && _coderTimer.IsEnabled)
            {
                _coderTimer.Stop();
            }
            GroupTHGrid.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void ClearGroupTH()
        {
            GroupTHUserPhoneTB.Text = string.Empty;
            GroupTHGroupIDTB.Text = string.Empty;
            GroupTHGroupNameTB.Text = string.Empty;
            GroupTHCustManagerIDTB.Text = string.Empty;
            GroupTHCustManagerNameTB.Text = string.Empty;
            GroupTHVerfyCodeTB.Text = string.Empty;
            GroupTHInfoTB.Text = GroupTHInfoTB.Tag.ToString();
            _code = string.Empty;
            GroupTHGrid.Tag = string.Empty;
        }
        #endregion
       
    }
}